﻿package com.platform.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.platform.server.common.Constant;
import com.platform.server.dao.EnterpriseDao;
import com.platform.server.dao.IdentityAuthenticationDao;
import com.platform.server.dao.MessageDao;
import com.platform.server.dao.PayOrderDao;
import com.platform.server.dao.ServerDao;
import com.platform.server.dao.UserDao;
import com.platform.server.dao.VideoDao;
import com.platform.server.dao.VipDao;
import com.platform.server.dao.VipSettingDao;
import com.platform.server.entity.DemandOrder;
import com.platform.server.entity.Order;
import com.platform.server.entity.ServerOrder;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.service.ServerService;
import com.platform.server.util.AuroraPush;
import com.platform.server.util.CfbpayDemoUtils3;
import com.platform.server.util.CfbpayDemoUtils5;
import com.platform.server.util.DateUtil;
import com.platform.server.util.DateUtils;
import com.platform.server.util.StringTools;
import com.platform.server.util.WxpayDemoUtils;
import com.platform.server.util.WxpayDemoUtils3;
import com.platform.server.util.WxpayDemoUtils5;
import com.szrca.ima.utils.LocationUtils;
import com.szrca.ima.utils.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServerServiceImpl implements ServerService {

    @Autowired
    private ServerDao serverDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private VipDao vipDao;

    @Autowired
    private VideoDao videoDao;

    @Autowired
    private PayOrderDao payOrderDao;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private IdentityAuthenticationDao identityAuthenticationDao;

    @Autowired
    private VipSettingDao vipSettingDao;
	@Autowired
	private EnterpriseDao enterpriseDao;
    /**
     * 选择类型列表
     */
    @Override
    public ReturnData selectServerList() {
        String servername = null;
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < 3; i++) {
            if (i == 0) {
                servername = "劳务";
            } else if (i == 1) {
                servername = "陪护";
            } else if (i == 2) {
                servername = "咨询";
            }
            List<Map<String, Object>> lists = serverDao.selectServerList(servername);
            if (i == 0) {
                map.put("labour", lists);
            } else if (i == 1) {
                map.put("accompany", lists);
            } else if (i == 2) {
                map.put("consult", lists);
            }
        }
        return new ReturnData(map, 200, "成功");
    }

    /**
     * 选择价格列表
     */
    @Override
    public ReturnData selectPriceList(Integer serverid) {
        if (serverid == null) {
            return new ReturnData(12, "参数有误");
        }
        List<Integer> lists = new ArrayList<>();
        Integer price = serverDao.selectPriceList(serverid);
        Integer topPrice = (int) (price * 0.7);
        for (; topPrice < price; topPrice++) {
            lists.add(topPrice);
        }
        Integer downPrice = (int) (price * 1.3);
        for (; downPrice >= price; price++) {
            lists.add(price);
        }
        return new ReturnData(lists, 200, "成功");
    }

    /**
     * 获取推荐需求列表
     */
    @Override
    public ReturnData selectRecommendDemand(String content, String longitude, String latitude) {
        if (StringTools.isEmpty(content) || StringTools.isEmpty(longitude) || StringTools.isEmpty(latitude)) {
            return new ReturnData(12, "参数有误");
        }
        List<Map<String, Object>> lists = serverDao.selectRecommendDemand();
        List<Map<String, Object>> arrayList = new ArrayList<>();
        for (int k = 0; k < lists.size(); k++) {
            O:
            for (int i = 0; i < content.length(); i++) {
                for (int j = 0; j < ((String) lists.get(k)
                                                   .get("details")).length(); j++) {
                    Character charAt = content.charAt(i);
                    Character charAt2 = ((String) lists.get(k)
                                                       .get("details")).charAt(j);
                    System.out.println(charAt.equals(charAt2));
                    if (content.charAt(i) == ((String) lists.get(k)
                                                            .get("details")).charAt(j)) {
                        //查看用户平均星级
                        Map<String, Object> hashMap = userDao.selectAvgLevel(lists.get(k)
                                                                                  .get("user_id")
                                                                                  .toString());
                        Double avg = 4D;
                        if (hashMap != null && (Long) hashMap.get("总条目数") != 0) {
                            Double sum = (Double) hashMap.get("总星级数");
                            Long count = (Long) hashMap.get("总条目数");
                            avg = sum / count.doubleValue();
                        }
                        lists.get(k)
                             .put("avg", avg);
                        //计算距离
                        Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                                .parseDouble(lists.get(k)
                                                  .get("latitude")
                                                  .toString()), Double.parseDouble(lists.get(k)
                                                                                        .get("longitude")
                                                                                        .toString()));
                        lists.get(k)
                             .put("distance", distance);
                        arrayList.add(lists.get(k));
                        break O;
                    }
                }
            }
        }
        if (arrayList.size() > 0) {
            return new ReturnData(arrayList, 200, "推荐需求列表");
        }
        return new ReturnData(100, "");
    }

    /**
     * 获取推荐服务列表
     */
    @Override
    public ReturnData selectRecommendServer(String content, String longitude, String latitude) {
        if (StringTools.isEmpty(content) || StringTools.isEmpty(longitude) || StringTools.isEmpty(latitude)) {
            return new ReturnData(12, "参数有误");
        }
        List<Map<String, Object>> lists = serverDao.selectRecommendServer();
        List<Map<String, Object>> arrayList = new ArrayList<>();
        for (int k = 0; k < lists.size(); k++) {
            O:
            for (int i = 0; i < content.length(); i++) {
                for (int j = 0; j < ((String) lists.get(k)
                                                   .get("details")).length(); j++) {
                    if (content.charAt(i) == ((String) lists.get(k)
                                                            .get("details")).charAt(j)) {
                        //查看用户平均星级
                        Map<String, Object> hashMap = userDao.selectAvgLevel(lists.get(k)
                                                                                  .get("user_id")
                                                                                  .toString());
                        Double avg = 4D;
                        if (hashMap != null && (Long) hashMap.get("总条目数") != 0) {
                            Double sum = (Double) hashMap.get("总星级数");
                            Long count = (Long) hashMap.get("总条目数");
                            avg = sum / count.doubleValue();
                        }
                        lists.get(k)
                             .put("avg", avg);
                        //计算距离
                        Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                                .parseDouble(lists.get(k)
                                                  .get("latitude")
                                                  .toString()), Double.parseDouble(lists.get(k)
                                                                                        .get("longitude")
                                                                                        .toString()));
                        lists.get(k)
                             .put("distance", distance);
                        arrayList.add(lists.get(k));
                        break O;
                    }
                }
            }
        }
        if (arrayList.size() > 0) {
            return new ReturnData(arrayList, 200, "推荐服务列表");
        }
        return new ReturnData(100, "");
    }

    /**
     * 获取服务列表
     */
    @Override
    public ReturnData selectServiceList(String type, String option, String longitude, String latitude, Integer pageSize, Integer pageNo, String details, String address) {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> lists = serverDao.selectServiceList(type, option, details,address);
        if (lists.size() == 0) {
            return new ReturnData(100, "暂无数据");
        }
        List<Map<String, Object>> vipList = new LinkedList<>();  //vip列表
        List<Map<String, Object>> notVipList = new LinkedList<>();  //非vip列表
        List<Map<String, Object>> LinkedList = new LinkedList<>();  //最终列表
        for (int i = 0; i < lists.size(); i++) {
            //计算距离
            Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                    .parseDouble(lists.get(i)
                                      .get("latitude")
                                      .toString()), Double.parseDouble(lists.get(i)
                                                                            .get("longitude")
                                                                            .toString()));
            lists.get(i)
                 .put("distance", distance);
            lists.get(i)
                 .put("price", Integer.parseInt(lists.get(i)
                                                     .get("price")
                                                     .toString()));
            if (lists.get(i)
                     .get("star_level") == null) {
                lists.get(i)
                     .put("star_level", 4);
            }
            if ((Long) lists.get(i)
                            .get("isvip") > 0) {
                vipList.add(lists.get(i));
            } else {
                notVipList.add(lists.get(i));
            }
        }
        if (StringTools.isEmpty(option)) {
            for (int i = 0; i < vipList.size(); i++) {
                LinkedList.add(vipList.get(i));
            }
            for (int i = 0; i < notVipList.size(); i++) {
                LinkedList.add(notVipList.get(i));
            }
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(LinkedList);
            return new ReturnData(LinkedList, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
        } else if ("1".equals(option)) {
            Collections.sort(lists, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return ((Integer) o1.get("distance")).compareTo((Integer) o2.get("distance"));
                }
            });
        } else if ("3".equals(option)) {
            Collections.sort(lists, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return ((Integer) o1.get("price")).compareTo((Integer) o2.get("price"));
                }
            });
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
        return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
    }

    /**
     * 获取需求列表
     */
    @Override
    public ReturnData selectDemandList(String type, String option, String longitude, String latitude, Integer pageSize, Integer pageNo, String details, String address) {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> lists = serverDao.selectDemandList(type, option, details,address);
        if (lists.size() == 0) {
            return new ReturnData(100, "暂无数据");
        }
        List<Map<String, Object>> vipList = new LinkedList<>();  //vip列表
        List<Map<String, Object>> notVipList = new LinkedList<>();  //非vip列表
        List<Map<String, Object>> LinkedList = new LinkedList<>();  //最终列表
        for (int i = 0; i < lists.size(); i++) {
            //计算距离
            Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                    .parseDouble(lists.get(i)
                                      .get("latitude")
                                      .toString()), Double.parseDouble(lists.get(i)
                                                                            .get("longitude")
                                                                            .toString()));
            lists.get(i)
                 .put("distance", distance);
            lists.get(i)
                 .put("price", Integer.parseInt(lists.get(i)
                                                     .get("price")
                                                     .toString()));
            if (lists.get(i)
                     .get("star_level") == null) {
                lists.get(i)
                     .put("star_level", 4);
            }
            if ((Long) lists.get(i)
                            .get("isvip") > 0) {
                vipList.add(lists.get(i));
            } else {
                notVipList.add(lists.get(i));
            }
        }
        if (StringTools.isEmpty(option)) {
            for (int i = 0; i < vipList.size(); i++) {
                LinkedList.add(vipList.get(i));
            }
            for (int i = 0; i < notVipList.size(); i++) {
                LinkedList.add(notVipList.get(i));
            }
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(LinkedList);
            return new ReturnData(LinkedList, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
        } else if ("1".equals(option)) {
            Collections.sort(lists, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return ((Integer) o1.get("distance")).compareTo((Integer) o2.get("distance"));
                }
            });
        } else if ("3".equals(option)) {
            Collections.sort(lists, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return ((Integer) o1.get("price")).compareTo((Integer) o2.get("price"));
                }
            });
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
        return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
    }

    /**
     * 发布服务
     */
    @Override
    public ReturnData publishServer(ServerOrder server) {
        if (StringTools.isEmpty(server.getServer_type()) || StringTools.isEmpty(server.getServer_sub_type())  ||
                StringTools.isEmpty(server.getPrice()) || StringTools.isEmpty(server.getDetails()) || StringTools.isEmpty(server.getUser_id()) ||
                StringTools.isEmpty(server.getLongitude()) || StringTools.isEmpty(server.getLatitude())  || StringTools.isEmpty(server.getIs_enterprise())) {
            return new ReturnData(12, "参数有误");
        }
        //查看用户身份证是否已经认证
        int counts = userDao.selectUserIdentity(server.getUser_id());
        String selectEnterUser = userDao.selectEnterUser(server.getUser_id());
        if(!StringTools.isEmpty(selectEnterUser)&&selectEnterUser.equals("1")){
        	counts=1;
        }
        if (counts == 0) {
            return new ReturnData(24, "请先进行身份认证");
        }
        
        if(StringTools.isEmpty(selectEnterUser)||!StringTools.isEmpty(selectEnterUser)&&!selectEnterUser.equals("1")){
    		List<Map<String,Object>> selectUserServer = serverDao.selectUserServer(server.getUser_id());
    		for (Map<String, Object> map2 : selectUserServer) {
    			if(map2.get("server_time")!=null){
    	        	        	try {
    	        					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");

    	        					Date date =  df.parse( map2.get("server_time").toString());
    	        					Date date2 = df.parse( map2.get("end_time").toString());
    	        					Date time =  df.parse(server.getTime());
    	        					if(time.getTime()>=date.getTime()&&time.getTime()<=date2.getTime()){
    	        	 				   return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        					}
    	        					Date time2 = df.parse(server.getEnd_time());
    	        					if(time2.getTime()>=date.getTime()&&time2.getTime()<=date2.getTime()){
    	        	 				   return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        					}
    	        					if(time2.getTime()>=date.getTime() &&time.getTime()<=date.getTime()){
    	        						   return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        					}
    	        				} catch (Exception e) {
    	        					// TODO Auto-generated catch block
    	        					  return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        				}
    	          }
    		}
    		
    	}
        
		/*//查看用户是否是vip
		Map<String, Object> map = vipDao.selectVipPage(server.getUser_id());
		if(map == null){
			return new ReturnData(24,"您还不是vip用户，请先成为vip");
		}*/
        int flag = serverDao.publishServer(server);
        if (flag == 1) {
            //添加订单
            Order order = new Order();
            order.setServer_id(server.getId()
                                     .toString());
            order.setServer_user_id(server.getUser_id());
            order.setPrice(server.getPrice());
            order.setOrder_type("1");
            order.setStatus("初始状态");
            String selectServerOrderId = serverDao.selectServerOrderId(order.getServer_id(),"1");
            int flag1=0;
            if(StringTools.isEmpty(selectServerOrderId)){
            	flag1 = serverDao.nowMake(order);
            }else{
            	flag1 =serverDao.updateNowMake(order);
            	  order.setId(Long.parseLong(selectServerOrderId));
            }
            //添加自己的消息
            Map<String, Object> hm = new HashMap<>();
            hm.put("title", "发布服务成功");
            hm.put("type", "1");
            hm.put("recevicer_id", server.getUser_id());
            hm.put("content", "发布服务成功");
            hm.put("record_id", server.getId()
                                      .toString());
            messageDao.insertMessage(hm);
            //添加推荐人消息
            List<Map<String, Object>> lists = serverDao.selectRecommendDemand();
            List<Map<String, Object>> arrayList = new ArrayList<>();
            for (int k = 0; k < lists.size(); k++) {
                O:
                for (int i = 0; i < server.getDetails()
                                          .length(); i++) {
                    for (int j = 0; j < ((String) lists.get(k)
                                                       .get("details")).length(); j++) {
                        Character charAt = server.getDetails()
                                                 .charAt(i);
                        Character charAt2 = ((String) lists.get(k)
                                                           .get("details")).charAt(j);
                        System.out.println(charAt.equals(charAt2));
                        if (server.getDetails()
                                  .charAt(i) == ((String) lists.get(k)
                                                               .get("details")).charAt(j)) {
                            arrayList.add(lists.get(k));
                            break O;
                        }
                    }
                }
            }
            for (int i = 0; i < arrayList.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", "您有一条新的服务信息");
                map.put("type", "1");
                map.put("recevicer_id", arrayList.get(i)
                                                 .get("user_id"));
                map.put("content", "您有一条新的服务信息");
                map.put("record_id", server.getId()
                                           .toString());
                messageDao.insertMessage(map);
                AuroraPush.pushTargetForDriver(arrayList.get(i)
                                                        .get("user_id")
                                                        .toString(), "您有一条新的服务信息!");
            }
            return new ReturnData(server.getDetails(), 200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 发布需求
     */
    @Override
    public ReturnData publishDemand(DemandOrder server) {
        if ((StringTools.isEmpty(server.getServer_type())) || (StringTools.isEmpty(server.getServer_sub_type())) || 
        	      (StringTools.isEmpty(server.getPrice())) || (StringTools.isEmpty(server.getDetails())) || (StringTools.isEmpty(server.getUser_id())) || 
        	      (StringTools.isEmpty(server.getLongitude())) || (StringTools.isEmpty(server.getLatitude()))) {
        	return new ReturnData(12, "参数有误");
        }
        //查看用户身份证是否已经认证
        int count = userDao.selectUserIdentity(server.getUser_id());
        String selectEnterUser = userDao.selectEnterUser(server.getUser_id());
        if(!StringTools.isEmpty(selectEnterUser)&&selectEnterUser.equals("1")){
        	count=1;
        }
        if (count == 0) {
            return new ReturnData(24, "请先进行身份认证");
        }
		/*//查看用户是否是vip
		Map<String, Object> map = vipDao.selectVipPage(server.getUser_id());
		if(map == null){
			return new ReturnData(24,"您还不是vip用户，请先成为vip");
		}*/
        server.setNumber(WxpayDemoUtils.getRandomString(16));
        int flag = serverDao.publishDemand(server);
        if (flag == 1) {
            //添加订单
            Order order = new Order();
            order.setServer_id(server.getId()
                                     .toString());
            order.setUser_id(server.getUser_id());
            order.setPrice(server.getPrice());
            order.setOrder_type("2");
            order.setStatus("初始状态");
            String selectServerOrderId = serverDao.selectServerOrderId(order.getServer_id(),"2");
            int flag1=0;
            if(StringTools.isEmpty(selectServerOrderId)){
            	flag1 = serverDao.nowMake(order);
            }else{
            	flag1 =serverDao.updateNowMake(order);
            	  order.setId(Long.parseLong(selectServerOrderId));
            }
            //添加自己的消息
            Map<String, Object> hm = new HashMap<>();
            hm.put("title", "发布需求成功");
            hm.put("type", "1");
            hm.put("recevicer_id", server.getUser_id());
            hm.put("content", "发布需求成功");
            hm.put("record_id", server.getId()
                                      .toString());
            messageDao.insertMessage(hm);
            List<Map<String, Object>> lists = serverDao.selectRecommendServer();
            List<Map<String, Object>> arrayList = new ArrayList<>();
            for (int k = 0; k < lists.size(); k++) {
                O:
                for (int i = 0; i < server.getDetails()
                                          .length(); i++) {
                    for (int j = 0; j < ((String) lists.get(k)
                                                       .get("details")).length(); j++) {
                        if (server.getDetails()
                                  .charAt(i) == ((String) lists.get(k)
                                                               .get("details")).charAt(j)) {
                            arrayList.add(lists.get(k));
                            break O;
                        }
                    }
                }
            }
            for (int i = 0; i < arrayList.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", "您有一条新的需求信息");
                map.put("type", "1");
                map.put("recevicer_id", arrayList.get(i)
                                                 .get("user_id"));
                map.put("content", "您有一条新的需求信息");
                map.put("record_id", server.getId()
                                           .toString());
                messageDao.insertMessage(map);
                AuroraPush.pushTargetForDriver(arrayList.get(i)
                                                        .get("user_id")
                                                        .toString(), "您有一条新的需求信息!");
            }
            return new ReturnData(server.getDetails(), 200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 关注服务
     */
    @Override
    public ReturnData concernServer(String userid, String serverid) {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(serverid)) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.concernServer(userid, serverid);
        if (flag == 1) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 取消关注服务
     */
    @Override
    public ReturnData cancelConcernServer(String userid, String serverid) {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(serverid)) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.cancelConcernServer(userid, serverid);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 需求资料详情
     */
    @Override
    public ReturnData selectDemandInfo(Integer id, String userid, String type, String longitude, String latitude) {
        if (id == null || StringTools.isEmpty(type)) {
            return new ReturnData(12, "参数有误");
        }
        Map<String, Object> hashMap = new HashMap<>();
        Map<String, Object> map = null;
        if ("1".equals(type)) {
            map = serverDao.selectDemandInfo(id);
            if (map == null) {
                return new ReturnData(100, "未找到该需求信息");
            }
            if(map.get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(map.get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			map.put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			map.put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            if (map.get("star_level") == null) {
                map.put("star_level", 4);
            }
            //查看是否是我关注的人
            int count = userDao.selectMyFansIsattention(userid, map.get("user_id")
                                                                   .toString());
            map.put("isAttention", count);
            //查看是否已经报名
            int apply = userDao.selectIsApply(userid, id.toString());
            map.put("apply", apply);
        } else if ("2".equals(type)) {
            //查看服务资料详情
            map = serverDao.selectServerInfo(id);
            if (map == null) {
                return new ReturnData(100, "未找到该服务信息");
            }
            if(map.get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(map.get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			map.put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			map.put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            if (map.get("star_level") == null) {
                map.put("star_level", 4);
            }
            //计算距离
            Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                    .parseDouble(map.get("latitude")
                                    .toString()), Double.parseDouble(map.get("longitude")
                                                                        .toString()));
            map.put("distance", distance);
            //查看是否是我关注的人
            int count = userDao.selectMyFansIsattention(userid, map.get("user_id")
                                                                   .toString());
            map.put("isAttention", count);
            //查看是否已经预约
            int appointment = userDao.selectIsappointment(userid, id.toString());
            //查看该服务是否被我预约
            int byAppointment = userDao.selectIsByappointment(userid, id.toString());
            map.put("byAppointment", byAppointment);
            map.put("appointment", appointment);
        } else {
            return new ReturnData(16, "类型有误");
        }
        List<Map<String, Object>> lists = videoDao.selectVideoList(map.get("user_id")
                                                                      .toString());
        hashMap.put("info", map);
        hashMap.put("videoList", lists);
        return new ReturnData(hashMap, 200, "成功");
    }

    /**
     * 确认预约
     */
    @Override
    public ReturnData sureMakeServer(String userid, String serverid, String type, String longitude, String latitude) {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(serverid) || StringTools.isEmpty(type) || StringTools.isEmpty(longitude) ||
                StringTools.isEmpty(latitude)) {
            return new ReturnData(12, "参数有误");
        }
        String selectUsertEnter = userDao.selectUsertEnter(userid);
        if(!StringTools.isEmpty(selectUsertEnter)&& selectUsertEnter.equals("1")){
        		return new ReturnData(20, "您是企业员工，无法进行该操作");
        }
        String selectEnterUser = userDao.selectEnterUser(userid);
        if(!StringTools.isEmpty(selectEnterUser) &&selectEnterUser.equals("1")){
            return new ReturnData(20, "您是企业用户，无法进行该操作");
        }
        Map<String, Object> user = userDao.selectUserIsRegister(userid);
        if (user.get("age")!=null&&StringTools.isEmpty(user.get("age").toString())) {
            return new ReturnData(20, "请先设置年龄");
        }
        String age1 = (String) user.get("age");
        if ("1".equals(type)) {
            //查看服务资料详情
            Map<String, Object> map = serverDao.selectServerInfo(Integer.parseInt(serverid));
            if (map == null) {
                return new ReturnData(100, "未找到该信息");
            }
            //查看年龄是否符合
            	if(map.get("age")!=null&&!StringTools.isEmpty( map.get("age").toString())){
            		   String[] ages = map.get("age").toString().split("-");
                       if (Integer.parseInt(age1) >= Integer.parseInt(ages[0]) && Integer.parseInt(age1) <= Integer.parseInt(ages[1])) {
                       }else{
                    	   return new ReturnData(19, "您的年龄不符合要求");
                       }
                       
            }
            //计算距离
            Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                    .parseDouble(map.get("latitude")
                                    .toString()), Double.parseDouble(map.get("longitude")
                                                                        .toString()));
            map.put("distance", distance);
            //查看用户积分
            String integral = serverDao.selectUserIntegral(userid);
            map.put("integral", integral);
            //查看每积分可以抵现多少元
            Map<String, Object> m = serverDao.selectIntegralWithdraw();
            if (m != null && !StringTools.isEmpty(integral)) {
                //Integral_arrival  1积分抵多少元
                String Integral_arrival = (String) m.get("Integral_arrival");
                Double Integral_money = Double.parseDouble(integral) * Double.parseDouble(Integral_arrival);
                DecimalFormat df = new DecimalFormat("#0.00");
                String format = df.format(Integral_money);
                map.put("Integral_money", format);
                String selectisVip1 = this.serverDao.selectisVip1(userid);
                String selectisVip2 = this.serverDao.selectisVip2(userid);
                Map<String, Object> selectRate = serverDao.selectRate();
                if (!StringTools.isEmpty(selectisVip1) && selectisVip1.equals("1")) {
                  map.put("vip_server_discount", selectRate.get("vip_user_discount").toString() + "%" );
                } else if (!StringTools.isEmpty(selectisVip2) && selectisVip2.equals("1")) {
                    map.put("vip_server_discount", selectRate.get("two_user_discount").toString()  + "%" );
                  }else{
                  map.put("vip_server_discount", "0%");
                }
            }
            //查看是否已经预约
            int appointment = userDao.selectIsappointment(userid, serverid.toString());
            map.put("appointment", appointment);
  /*          String selectisVip = serverDao.selectisVip(userid);
            if(!StringTools.isEmpty(selectisVip)&&selectisVip.equals("1")){
            	   map.put("VipDiscont", serverDao.selectVipUserDiscont());
            }*/
            return new ReturnData(map, 200, "成功");
        } else if ("2".equals(type)) {
            //查看需求资料详情
            Map<String, Object> map = serverDao.selectDemandInfo(Integer.parseInt(serverid));
            if (map == null) {
                return new ReturnData(100, "未找到该信息");
            }
	/*if(StringTools.isEmpty(selectEnterUser)||!StringTools.isEmpty(selectEnterUser)&&!selectEnterUser.equals("1")){
		List<Map<String,Object>> selectUserServer = serverDao.selectUserServer(userid);
		for (Map<String, Object> map2 : selectUserServer) {
			if(map2.get("server_time")!=null){
	        	        	try {
	        					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");

	        					Date date =  (Date) map2.get("server_time");
	        					Date date2 = (Date) map2.get("end_time");
	        					Date time = (Date) map.get("time");
	        					if(time.getTime()>=date.getTime()&&time.getTime()<=date2.getTime()){
	        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
	        					}
	        					Date time2 = (Date) map.get("end_time");
	        					if(time2.getTime()>=date.getTime()&&time2.getTime()<=date2.getTime()){
	        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
	        					}
	        				} catch (Exception e) {
	        					// TODO Auto-generated catch block
	        					  return new ReturnData(12, "最多只能预约当前服务时长!");	
	        				}
	          }
		}
		
	}*/

            //查看年龄是否符合
//         	if(map.get("age")!=null&&!StringTools.isEmpty(map.get("age").toString())){
//                String[] ages = map.get("age").toString().split("-");
//                if (Integer.parseInt(age1) >= Integer.parseInt(ages[0]) && Integer.parseInt(age1) <= Integer.parseInt(ages[1])) {
//                   
//                }else{
//                	 return new ReturnData(19, "您的年龄不符合要求");
//                }
//     }
            //计算距离
            Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                    .parseDouble(map.get("latitude")
                                    .toString()), Double.parseDouble(map.get("longitude")
                                                                        .toString()));
            map.put("distance", distance);
            //查看用户积分
            String integral = serverDao.selectUserIntegral(userid);
            map.put("integral", integral);
            //查看每积分可以抵现多少元
            Map<String, Object> m = serverDao.selectIntegralWithdraw();
            if (m != null && !StringTools.isEmpty(integral)) {
                //Integral_arrival  1积分抵多少元
                String Integral_arrival = (String) m.get("Integral_arrival");
                Double Integral_money = Double.parseDouble(integral) * Double.parseDouble(Integral_arrival);
                DecimalFormat df = new DecimalFormat("#0.00");
                String format = df.format(Integral_money);
                map.put("Integral_money", format);
                String selectisVip1 = this.serverDao.selectisVip1(userid);
                String selectisVip2 = this.serverDao.selectisVip2(userid);
                Map<String, Object> selectRate = serverDao.selectRate();
                if (!StringTools.isEmpty(selectisVip1) && selectisVip1.equals("1")) {
                  map.put("vip_server_discount", selectRate.get("vip_user_discount").toString() + "%" );
                } else if (!StringTools.isEmpty(selectisVip2) && selectisVip2.equals("1")) {
                    map.put("vip_server_discount", selectRate.get("two_user_discount").toString()  + "%" );
                  }else{
                  map.put("vip_server_discount", "0%");
                }
            }
            //查看是否已经报名
            int apply = userDao.selectIsApply(userid, serverid.toString());
            
            map.put("apply", apply);
       /*     String selectisVip = serverDao.selectisVip(userid);
            if(!StringTools.isEmpty(selectisVip)&&selectisVip.equals("1")){
            	   map.put("vipDiscont", serverDao.selectVipUserDiscont());
            }*/
            return new ReturnData(map, 200, "成功");
        }
        return new ReturnData(10, "参数type有误");
    }

    /**
     * 预约
     */
    @Override
    public ReturnData nowMake(Order order) {
        if (StringTools.isEmpty(order.getServer_id()) || StringTools.isEmpty(order.getUser_id()) || StringTools.isEmpty(order.getPrice()) || StringTools.isEmpty(order.getEnd_time()) ||
                StringTools.isEmpty(order.getHours()) || StringTools.isEmpty(order.getMobile()) || StringTools.isEmpty(order.getServer_time()) ||
                StringTools.isEmpty(order.getServer_address()) || StringTools.isEmpty(order.getSum_price()) || StringTools.isEmpty(order.getVip_discount()) ||
                StringTools.isEmpty(order.getIntegral()) || StringTools.isEmpty(order.getReality_price()) || StringTools.isEmpty(order.getOrder_type())
                || StringTools.isEmpty(order.getServer_user_id())) {
            return new ReturnData(12, "参数有误");
        }
        Map<String, Object> selectIntegralWithdraw = serverDao.selectIntegralWithdraw();
        if(selectIntegralWithdraw.get("Integral_arrival")!=null&&selectIntegralWithdraw.get("Integral_arrival").toString().lastIndexOf(".")!=-1){
        String sd=	selectIntegralWithdraw.get("Integral_arrival").toString().substring(selectIntegralWithdraw.get("Integral_arrival").toString().indexOf("."),selectIntegralWithdraw.get("Integral_arrival").toString().length());
        if(sd.length()==3){
        	  Double valueOf = Double.valueOf(order.getIntegral());
          	  valueOf= valueOf*100;
          	   DecimalFormat dff = new DecimalFormat("#.00");  
          	  String integral=dff.format(valueOf);
          	  if(valueOf.toString().lastIndexOf(".")!=-1){
          		     integral=integral.substring(0, integral.lastIndexOf("."));
          		   order.setIntegral(integral);
          	  }
        }
        if(sd.length()==2){
        	Double valueOf = Double.valueOf(order.getIntegral());
        	  valueOf= valueOf*10;
        	   DecimalFormat dff = new DecimalFormat("#.0");  
        	  String integral=dff.format(valueOf);
        	  if(valueOf.toString().lastIndexOf(".")!=-1){
        		     integral=integral.substring(0, integral.lastIndexOf("."));
        		   order.setIntegral(integral);
        	  }	
        }
        }
      
        /*   if(order.getOrder_type().equals("1")){
        	   String selectEnterUser = userDao.selectEnterUser(order.getServer_user_id());
        		if(StringTools.isEmpty(selectEnterUser)||!StringTools.isEmpty(selectEnterUser)&&!selectEnterUser.equals("1")){
        			List<Map<String,Object>> selectUserServer = serverDao.selectUserServer(order.getServer_user_id());
        			for (Map<String, Object> map2 : selectUserServer) {
        				if(map2.get("server_time")!=null){
        		        	        	try {
        		        					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");

        		        					Date date =  (Date) map2.get("server_time");
        		        					Date date2 = (Date) map2.get("end_time");
        		        					Date time = df.parse(order.getServer_time());
        		        					if(time.getTime()>=date.getTime()&&time.getTime()<=date2.getTime()){
        		        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
        		        					}
        		        					Date time2 = df.parse(order.getEnd_time());
        		        					if(time2.getTime()>=date.getTime()&&time2.getTime()<=date2.getTime()){
        		        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
        		        					}
        		        				} catch (Exception e) {
        		        					// TODO Auto-generated catch block
        		        					  return new ReturnData(12, "最多只能预约当前服务时长!");	
        		        				}
        		          }
        			}
        		}
        }
        if(order.getOrder_type().equals("2")){
        	List<Map<String,Object>> selectUserServer = serverDao.selectUserServer(order.getServer_user_id());
			for (Map<String, Object> map2 : selectUserServer) {
				if(map2.get("server_time")!=null){
		        	        	try {
		        					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");

		        					Date date =  (Date) map2.get("server_time");
		        					Date date2 = (Date) map2.get("end_time");
		        					Date time = df.parse(order.getServer_time());
		        					if(time.getTime()>date.getTime()&&time.getTime()<date2.getTime()){
		        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
		        					}
		        					Date time2 = df.parse(order.getEnd_time());
		        					if(time2.getTime()>date.getTime()&&time2.getTime()<date2.getTime()){
		        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
		        					}
		        					if(date.getTime()>time.getTime()&&date.getTime()<time2.getTime()){
			        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
			        				}
		        					if(date2.getTime()>time.getTime()&&date2.getTime()<time2.getTime()){
			        	 				   return new ReturnData(12, "最多只能预约当前服务时长!");	
			        				}
		        				} catch (Exception e) {
		        					// TODO Auto-generated catch block
		        					  return new ReturnData(12, "最多只能预约当前服务时长!");	
		        				}
		          }
			}
    			
        }*/
        order.setOrder_id(WxpayDemoUtils.getRandomString(16));
       List<Map<String,Object>> selectServerOrder = serverDao.selectServerOrder(order.getServer_id(),order.getOrder_type());
       if(selectServerOrder.size()>1){
    	   for (int i = selectServerOrder.size()+1; i < selectServerOrder.size(); i--) {
    		   if(i==1){
    			   serverDao.deleteOrder(selectServerOrder.get(i).get("id").toString());
    		   }
    	   }
       }
        String selectServerOrderId = serverDao.selectServerOrderId(order.getServer_id(),order.getOrder_type());
        int flag=0;
        if(StringTools.isEmpty(selectServerOrderId)){
        	  flag = serverDao.nowMake(order);
        }else{
        	  flag =serverDao.updateNowMake(order);
        	  order.setId(Long.parseLong(selectServerOrderId));
        }
       
        if (flag > 0) {
            if ("0".equals(order.getReality_price())) {
                //修改订单状态为已支付
                int f = payOrderDao.updateOrderStatus(order.getOrder_id());
                if (!StringTools.isEmpty(order.getDiscountid())) {
                    //修改优惠券为已使用
                    payOrderDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
                }
                if (!StringTools.isEmpty(order.getIntegral())&&order.getIntegral() != "0") {
                    int flag2 = payOrderDao.updateUserIntegrals(order.getUser_id(),order.getIntegral());

                    //最后添加该用户的积分记录
                    serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分抵现", null);

                }
                serverDao.deletedDemandApplyUser(order.getServer_id(), order.getServer_user_id());
                Map<String, Object> map = new HashMap<>();
                map.put("orderid", order.getOrder_id());
                map.put("id", order.getId());
                return new ReturnData(order.getId(), 201, "成功");
            }
            serverDao.deletedDemandApplyUser(order.getServer_id(), order.getServer_user_id());
            Map<String, Object> map = new HashMap<>();
            map.put("orderid", order.getOrder_id());
            map.put("id", order.getId());
            return new ReturnData(map, 200, "成功");
        }
        return null;
    }

    /**
     * 关注需求
     */
    @Override
    public ReturnData concernDemand(String userid, String demandid) {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(demandid)) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.concernDemand(userid, demandid);
        if (flag == 1) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 取消关注需求
     */
    @Override
    public ReturnData cancelConcernDemand(String userid, String demandid) {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(demandid)) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.cancelConcernDemand(userid, demandid);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 档期
     */
    @Override
    public ReturnData cancelOrder(Integer orderid, String userid, String type) throws Exception {
        if (orderid == null || userid == null) {
            return new ReturnData(12, "参数有误");
        }
        //查看订单详情
        Order order = serverDao.selectOrderInfo(orderid);
        if (order == null) {
            return new ReturnData(100, "未找到相关信息");
        }
    	Long time = System.currentTimeMillis();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
			Date dt1 = df.parse(order.getServer_time());
			if(new Date().getTime()>dt1.getTime()){
				if(order.getServer_user_id().equals(userid)){
					 return new ReturnData(100, "请选择支付方式");
				}
				  if (!StringTools.isEmpty(order.getDiscountid())) {
			            //修改优惠券状态
			            serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
			        }
				  String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
		        	if(Double.valueOf(order.getReality_price())>0){
			        	selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price().substring(0,order.getReality_price().indexOf("."))));
			            serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
			            serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
		        	}
			        if (!StringTools.isEmpty(order.getIntegral())) {
			            //退还用户积分
			            serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
			            //最后添加该用户的积分记录
			            serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);
			        }
			       String str="服务违约支出";
		            String str1="服务方违约金收入";
		            /*if(order.getUser_id().equals(userid)){
		        		if(!order.getStatus().equals("服务中")){
		        			order.setUser_id(order.getServer_user_id());
			        		order.setServer_user_id(userid);
			        		   str="需方违约支出";
					             str1="需方违约金收入";
		        		}
		        	
		        	}*/
				   Map<String, Object> map1 = serverDao.selectUserMoney("1");
		            String platform_money = map1.get("money")
		                                        .toString();
				 //  1 先获取服务方的钱包
	            Map<String, Object> map3 = serverDao.selectUserMoney(order.getServer_user_id());
	            String server_money = map3.get("money")
	                                      .toString();
	        if (Double.valueOf(server_money) >= 30) {
	        	  // 2 扣除服务方违约金
	            serverDao.insertCancelOrder(order.getServer_user_id(), "30", "服务违约支出", order.getOrder_id(), Double.valueOf(server_money) - Double.valueOf("30") + "", Constant.EXPEND, platform_money, null);
	            serverDao.returnUserMoney(order.getServer_user_id(), Double.valueOf(server_money) - Double.valueOf("30") + "");
	            // 3 需求方获取违约金
	            Map<String, Object> map4 = serverDao.selectUserMoney(order.getUser_id());
	            String user_money = map4.get("money")
	                                    .toString();
	            serverDao.insertCancelOrder(order.getUser_id(), "30", "服务方违约金收入", order.getOrder_id(), Double.valueOf(user_money) + Double.valueOf("30") + "", Constant.INCOME, platform_money, null);
	            serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money) + Double.valueOf("30") + "");
	            // 4 需求方获取订单返回金额
	            Map<String, Object> map5 = serverDao.selectUserMoney(order.getUser_id());
	            String user_money1 = map5.get("money")
	                                     .toString();
	            Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
	            if(selectCancelOrder==null){
	            	 serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "", Constant.INCOME, Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", null);
	 	            serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "");
	 	            // 5 平台返回订单金额
	 	            //  serverDao.insertCancelOrder("1", order.getReality_price(), "平台预付返还", order.getOrder_id(), Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", Constant.EXPEND);
	 	            serverDao.returnUserMoney("1", Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "");
	           
	            }
	           	            } else {
	                // 或者新增违约金记录 （用于充值的时候进行扣除）
	                serverDao.insertViolate(30.00, order.getServer_user_id(), order.getOrder_id(),order.getUser_id() );
	            }
	            int flag4 = serverDao.cancelOrder(orderid);
	            if (flag4 > 0) {
	                return new ReturnData(200, "取消订单成功!");
	            }
			}
        } catch (ParseException e) {
			// TODO Auto-generated catch block)%_(
			e.printStackTrace();
		}
        // 开始时间
        Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(order.getServer_time());
        Long start_time = date1.getTime();
        // 结束时间
        Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(order.getEnd_time());
        Long end_time = date2.getTime();
        Long nowTime = System.currentTimeMillis();
        String uid = null;
        if ((start_time - nowTime) <= (60 * 60 * 1000 * 2)) {
            return new ReturnData(100, "请选择支付方式");
        }
      /*  if ((nowTime - end_time) > (30 * 60 * 1000)) {
            return new ReturnData(100, "请选择支付方式");
        }*/
        if (!StringTools.isEmpty(order.getDiscountid())) {
            //修改优惠券状态
            serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
        }
    	String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
    	if(Double.valueOf(order.getReality_price())>0){

        	selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price().substring(0,order.getReality_price().indexOf("."))));
            serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
            serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
        	}
        if (!StringTools.isEmpty(order.getIntegral())) {
        	//退还用户积分
            serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
            //最后添加该用户的积分记录
            serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);        }
        
        //查看用户余额
        Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getUser_id());
        Double money = (Double) selectUserMoney.get("money");
        Double realityMoney = Double.parseDouble(order.getReality_price()) + money;
        // 先把订单的钱退回
        String s = userDao.selectUserMoney("1");

        Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
        if(selectCancelOrder==null){
            serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), realityMoney + "", Constant.INCOME, Double.valueOf(s) - Double.valueOf(order.getReality_price()) + "", null);
            serverDao.returnUserMoney("1", Double.valueOf(s) - Double.valueOf(order.getReality_price()) + "");
            serverDao.returnUserMoney(order.getUser_id(), realityMoney.toString());   
        }

        if(new Date().getTime()>=start_time){
    	// 在查询对方是否余额是否够30元
          Map<String, Object> stringObjectMap = serverDao.selectUserMoney(order.getServer_user_id());
          Double money1 = (Double) stringObjectMap.get("money");
          Double money2 = money1 + 30;
           selectUserMoney = serverDao.selectUserMoney(order.getUser_id());
           money = (Double) selectUserMoney.get("money");
          if (money >= 30) {
              serverDao.insertCancelOrder(order.getServer_user_id(), "30", "需方违约收入", order.getOrder_id(), money2 + "", Constant.INCOME, Double.valueOf(s) - Double.valueOf(order.getReality_price()) +"", null);
              serverDao.returnUserMoney(order.getServer_user_id(), money2.toString());
              Double money3 = money - 30;
              serverDao.insertCancelOrder(order.getUser_id(), "30", "需方违约支出", order.getOrder_id(), money3 + "", Constant.EXPEND, Double.valueOf(s) - Double.valueOf(order.getReality_price())+"", null);
              serverDao.returnUserMoney(order.getServer_user_id(), money3.toString());
          } else {
              // 或者新增违约金记录 （用于充值的时候进行扣除）
              serverDao.insertViolate(30.00, order.getUser_id(), order.getOrder_id(), order.getServer_user_id());
          } 
      }
        int flag4 = serverDao.cancelOrder(orderid);
        if (flag4 > 0) {
            return new ReturnData(200, "取消订单成功!");
        }
        
        /* // 平台余额
        Map<String, Object> map = serverDao.selectUserMoney("1");
        Double platform_money = (Double) map.get("money");
        //添加自己的消息
        insertMsg(userid, order);
        //查看用户余额
        Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getUser_id());
        Double money = (Double) selectUserMoney.get("money");
        Double realityMoney = Double.parseDouble(order.getReality_price()) + money;
        //退还用户金额
        int flag3 = serverDao.returnUserMoney(order.getUser_id(), realityMoney.toString());
        serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), realityMoney + "", Constant.INCOME, platform_money - Double.valueOf(order.getReality_price()) + "", null);
        //serverDao.insertCancelOrder("1", realityMoney.toString(), "平台预付返还", order.getOrder_id(), platform_money - realityMoney + "", Constant.EXPEND);
        serverDao.returnUserMoney("1", platform_money - Double.valueOf(order.getReality_price()) + "");
        if (flag3 > 0) {
            //修改订单状态
            int flag4 = serverDao.cancelOrder(orderid);
            if (flag4 > 0) {
                return new ReturnData(200, "取消成功");
            }
        }*/
        return new ReturnData(19, "取消失败");
    }

    public void insertMsg(String userid, Order order) {
        //添加自己的消息
        Map<String, Object> hm = new HashMap<>();
        hm.put("title", "您的订单已取消");
        hm.put("type", "1");
        hm.put("recevicer_id", order.getUser_id());
        hm.put("content", "您的订单已取消");
        messageDao.insertMessage(hm);
        Map<String, Object> map = new HashMap<>();
        map.put("title", "您的订单已取消");
        map.put("type", "1");
        map.put("recevicer_id", order.getServer_user_id());
        map.put("content", "您的订单已取消");
        messageDao.insertMessage(map);
        if (userid.equals(order.getUser_id())) {
            AuroraPush.pushTargetForDriver(order.getServer_user_id(), "您的订单已取消");
        } else {
            AuroraPush.pushTargetForDriver(order.getUser_id(), "您的订单已取消");
        }
    }

    @Override
    public ReturnData isLate(Integer orderid) {
        Order order = serverDao.selectOrderInfo(orderid);
        if (order != null) {
            // 开始时间
            Date startTime = null;
            try {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(order.getServer_time());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (System.currentTimeMillis() >= startTime.getTime()) {
                return new ReturnData(100, "已迟到");
            } else {
                return new ReturnData(200, "开始服务");
            }
        }
        return new ReturnData(101, "订单数据不存在");
    }

    /**
     * 档期确认完成
     */
    @Override
    public ReturnData confirmOrder(Integer orderid, Integer type) {
        if (orderid == null || (type != 1 && type != 2)) {
            return new ReturnData(12, "参数有误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderid", orderid);
        if (type == 1) {
            map.put("status", "已完成");
        } else {
            map.put("status", "待评价");
        }
        int flag = serverDao.confirmOrder(map);
        if (flag > 0) {
            //查看订单详情
            Order order = serverDao.selectOrderInfo(orderid);
            //修改该服务单号为已完成
            int flag1 = serverDao.updateServerStatus(Integer.parseInt(order.getServer_id()));
            if (flag1 > 0) {
             
                return new ReturnData(200, "成功");
            }
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 档期删除
     */
    @Override
    public ReturnData deleteServerOrder(Integer serverid, String retractor) {
        if (serverid == null || retractor == null) {
            return new ReturnData(12, "参数有误");
        }
        //查看订单详情
        Order order = serverDao.selectOrderInfo(serverid);
        if (StringTools.isEmpty(order.getRetractor())) {
            order.setRetractor(retractor);
            order.setId(serverid.longValue());
            serverDao.updateOrderRetractor(order);
        } else {
            order.setRetractor(order.getRetractor() + "," + retractor);
            order.setId(serverid.longValue());
            serverDao.updateOrderRetractor(order);
            int flag = serverDao.deleteServerOrder(serverid);
        }
        return new ReturnData(200, "成功");
    }

    /**
     * 需求确认完成
     */
    @Override
    public ReturnData demandSure(Integer demandid, Integer orderid) {
        if (orderid == null) {
            return new ReturnData(12, "参数有误");
        }
        Order order = serverDao.selectOrderInfo(orderid);
        if(order.getStatus().equals("已完成")){
            return new ReturnData(12, "订单已完成");
        }
        int flag = serverDao.demandSure(demandid);
        Map<String, Object> map = new HashMap<>();
        map.put("status", "已完成");
        map.put("orderid", orderid);
        serverDao.confirmOrder(map);
        //查看订单详情
         order = serverDao.selectOrderInfo(orderid);
        String server_user_id = order.getServer_user_id();
        Double sum_price = Double.parseDouble(order.getSum_price());
        Double money = 0D;
        Double dismoney = 0D;
        //查看平台手续费
        DecimalFormat df = new DecimalFormat("######0.00");
        Double discount = serverDao.selectPlatformDiscount();
        if (discount > 0) {
            money = Double.parseDouble(df.format(sum_price * (discount / 100)));
        	dismoney=money;
        }
        Map<String, Object> selectRate = serverDao.selectRate();
        //查看vip服务费折扣
        String selectisVip1 = serverDao.selectisVip1(order.getServer_user_id());
        String selectisVip2 = serverDao.selectisVip2(order.getServer_user_id());
        if(!StringTools.isEmpty(selectisVip1)&&selectisVip1.equals("1")){
        	Double selectVipDiscont = serverDao.selectVipDiscont();
        	money = Double.parseDouble(df.format(money * (selectVipDiscont / 100)));
        }
        if(!StringTools.isEmpty(selectisVip2)&&selectisVip2.equals("1")){
        	Double selectVipDiscont = Double.parseDouble(selectRate.get("two_vip_discount").toString());
        	money = Double.parseDouble(df.format(money * (selectVipDiscont / 100)));
        }
        //查看企业会员服务费折扣
       int selectUserAuthentication = userDao.selectUserAuthentication(order.getServer_user_id());
       if(selectUserAuthentication==1){
    	   if(dismoney!=money){
    		   money=dismoney;
    	   }
    	   String selectis_vip = userDao.selectis_vip(order.getServer_user_id(), "2");
    	   if(!StringTools.isEmpty(selectis_vip)&&selectis_vip.equals("1")){
    		   Double selectEntUserDiscont = serverDao.selectEntUserDiscont();
   		 	money = Double.parseDouble(df.format(money * (selectEntUserDiscont / 100)));  
    	   }
    	 
       }
        Double _money = sum_price - money;
        // 平台余额
        Map<String, Object> map2 = serverDao.selectUserMoney("1");
        String platform_money = map2.get("money")
                                    .toString();

        // 服务者的余额
        Map<String, Object> map1 = serverDao.selectUserMoney(server_user_id);
        String money1 = map1.get("money")
                            .toString();
        // 需求者的余额
        Map<String, Object> map3 = serverDao.selectUserMoney(order.getUser_id());
        String money2 = map3.get("money")
                            .toString();
        Double royaltytotal = 0D;
        Double royaltytotal2 = 0D;
        //royaltytotal += royalty(order.getServer_user_id(), order, platform_money, money1,_money);
       // royaltytotal += royalty(order.getServer_user_id(), order, platform_money, money1,Double.parseDouble(order.getReality_price()));

        map1 = serverDao.selectUserMoney(server_user_id);
         money1 = map1.get("money")
                            .toString();
        // 需求者的余额
        map3 = serverDao.selectUserMoney(order.getUser_id());
         money2 = map3.get("money")
                            .toString();

        royaltytotal += royalty(order.getUser_id(), order, platform_money, money2,Double.parseDouble(order.getReality_price()));
        map1 = serverDao.selectUserMoney(server_user_id);
        money1 = map1.get("money")
                           .toString();
       // 需求者的余额
        platform_money=Double.valueOf(platform_money)-royaltytotal+"";
        int selectUserAuthentication2 = userDao.selectUserAuthentication(order.getServer_user_id());
        if(selectUserAuthentication2==1){
        	String selectis_vip = userDao.selectis_vip(order.getServer_user_id(), "2");
        	 if(!StringTools.isEmpty(selectis_vip)&&selectis_vip.equals("1")){
        			Map<String, Object> selectRate2 = serverDao.selectRate();
        	  	 Double selectRate3 = Double.parseDouble( selectRate2.get("ent_pay").toString());
        	  	Double  royalty = Double.parseDouble(df.format(sum_price * (selectRate3 / 100)));
        	  	platform_money=Double.valueOf(platform_money) -royalty+"";
        		  serverDao.insertRoyaltyOrder(order.getServer_user_id(), royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME,  Double.valueOf(platform_money)+ "" , null,serverDao.selectOrderSend(order.getOrder_id()));
	    		  //加入提成
	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
	    	        hashMap.put("user_id", order.getServer_user_id());
	    	        hashMap.put("money", royalty);
	    	        serverDao.updateServerUserMoney(hashMap);
        	}
        }
       map1 = serverDao.selectUserMoney(server_user_id);
         money1 = map1.get("money")
                            .toString();
         royaltytotal2 += royalty(order.getServer_user_id(), order, platform_money, money1, _money);
         platform_money=Double.valueOf(platform_money)-royaltytotal2+"";
        serverDao.insertCancelOrder(server_user_id, _money + "", "完成", order.getOrder_id(), Double.valueOf(money1) + _money + "", Constant.INCOME, Double.valueOf(platform_money) - _money + "", sum_price - _money + "");
        //加入服务者余额
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("user_id", server_user_id);
        hashMap.put("money", _money);
        serverDao.updateServerUserMoney(hashMap);
        // serverDao.insertCancelOrder(order.getUser_id() + "", sum_price + "", "需求完成", order.getOrder_id(), Double.valueOf(money2) + "", Constant.EXPEND, Double.valueOf(platform_money) + "", null);
        serverDao.returnUserMoney("1", Double.valueOf(platform_money) - _money+ "");
        //serverDao.insertCancelOrder("1", sum_price - _money + "", "平台手续费", order.getOrder_id(), Double.valueOf(platform_money) - _money + "", Constant.INCOME);
        //查看积分使用方式
        Map<String, Object> hashMap1 = userDao.selectIntegeralWay();
        //查看用户积分
        Map<String, Object> hm = userDao.selectMyIntegral(order.getServer_user_id());
        Integer integral = Integer.parseInt(hm.get("integral")
                                              .toString()) + Integer.parseInt(hashMap1.get("server")
                                                                                     .toString());
        //服务完成后给该用户增加积分
        int flag2 = serverDao.updateIntegral(order.getServer_user_id(), integral.toString());
        //最后添加该用户的积分记录
        int flag3 = serverDao.insertIntegralRecord(order.getServer_user_id(), hashMap1.get("server")
                                                                                     .toString(), "服务完成", null);
        return new ReturnData(200, "成功");
    }
    //提成
    public Double royalty(String user_id,Order order,String platform_money,String money1,Double money2){
    	  Double royaltytotal = 0D;
    	 DecimalFormat df = new DecimalFormat("######0.00");
    	 //查询上一级用户
        String selectParent = userDao.selectParent(user_id);
		Map<String, Object> selectRate2 = serverDao.selectRate();
		  Double royalty = 0D;
        if(!StringTools.isEmpty(selectParent)){
   	    	  //查看顶级是否企业
//      	       int selectUserAuthentication2 = userDao.selectUserAuthentication(user_id);
   	    	  //查询顶级是否vip
   	    	  String selectEntMember1 = serverDao.selectisVip1(selectParent);
   	    	  String selectEntMembe2 = serverDao.selectisVip2(selectParent);
   	    	  //加入提成
   	    	  if(!StringTools.isEmpty(selectEntMember1)&&selectEntMember1.equals("1")){
//   	    		  	if(selectUserAuthentication2==1){
//   	    		  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_ent_level").toString());
//     	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
//     	    		  serverDao.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,user_id);
//     	    		  //加入提成
//   	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
//   	    	        hashMap.put("user_id", selectParent);
//   	    	        hashMap.put("money", royalty);
//   	    	        serverDao.updateServerUserMoney(hashMap);
//   	    		  	}else{
   	    		  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_one_level").toString());
        	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
        	    		  platform_money=  Double.valueOf(platform_money) -royalty+"";
        	    	        Map<String, Object> map1 = serverDao.selectUserMoney(selectParent);
        	    	         money1 = map1.get("money")
        	    	                            .toString();
        	    		  serverDao.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME, platform_money, null,user_id);
        	    		  //加入提成
       	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
       	    	        hashMap.put("user_id", selectParent);
       	    	        hashMap.put("money", royalty);
       	    	        serverDao.updateServerUserMoney(hashMap);
       	    	        
       	    	  	royaltytotal=royalty; 
//   	    		  	}
   	    	  }else if(!StringTools.isEmpty(selectEntMembe2)&&selectEntMembe2.equals("1")){
// 	    		  	if(selectUserAuthentication2==1){
// 	   	    		  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_ent_level").toString());
// 	     	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
// 	     	    		  serverDao.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,user_id);
// 	     	    		  //加入提成
// 	   	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
// 	   	    	        hashMap.put("user_id", selectParent);
// 	   	    	        hashMap.put("money", royalty);
// 	   	    	        serverDao.updateServerUserMoney(hashMap);
// 	   	    		  	}else{
 	   	    		  	 Double selectRate = Double.parseDouble( selectRate2.get("two_vip_one").toString());
 	        	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
 	        	    		  platform_money=  Double.valueOf(platform_money) -royalty+"";
  	        	    	    Map<String, Object> map1 = serverDao.selectUserMoney(selectParent);
       	    	         money1 = map1.get("money")
       	    	                            .toString();
 	        	    		  serverDao.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME,platform_money , null,user_id);
 	        	    		  //加入提成
 	       	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
 	       	    	        hashMap.put("user_id", selectParent);
 	       	    	        hashMap.put("money", royalty);
 	       	    	        serverDao.updateServerUserMoney(hashMap);
 	       	    	 	royaltytotal=royalty;
// 	   	    		  	}
 	   	    	  }else{
//   	    		 	if(selectUserAuthentication2==1){
//   	    		 		 Double selectRate = Double.parseDouble( selectRate2.get("ordinary_ent_level").toString());
//   	    	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
//   	    	    		  serverDao.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,user_id);
//   	    	    		 //加入提成
//   	    	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
//   	    	    	        hashMap.put("user_id", selectParent);
//   	    	    	        hashMap.put("money", royalty);
//   	    	    	        serverDao.updateServerUserMoney(hashMap);
//   	    		 	}else{
     	    			 Double selectRate = Double.parseDouble( selectRate2.get("ordinary_one_level").toString());
      	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
      	    		  platform_money=  Double.valueOf(platform_money) -royalty+"";
      	    	    Map<String, Object> map1 = serverDao.selectUserMoney(selectParent);
	    	         money1 = map1.get("money")
	    	                            .toString();
      	    		  serverDao.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME, platform_money, null,user_id);
      	    		 //加入提成
       	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
       	    	        hashMap.put("user_id", selectParent);
       	    	        hashMap.put("money", royalty);
       	    	        serverDao.updateServerUserMoney(hashMap);
       	    	  	royaltytotal=royalty;
//   	    		 	}
   	    	  }
        	
   	    	//royaltytotal=royalty;
     	   //查询是否二级
     	      String parent = userDao.selectParent(selectParent);
     	      if(!StringTools.isEmpty(parent)){
     	    	 royalty=0.D;
     	    	  //查询顶级是否vip
     	    	  String selectEntMember21 = serverDao.selectisVip1(parent);
     	    	  String selectEntMember22 = serverDao.selectisVip2(parent);
     	    	//加入提成
     	    	  if(!StringTools.isEmpty(selectEntMember21)&&selectEntMember21.equals("1")){
     	    	  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_two_level").toString());
     	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
     	    		  platform_money=  Double.valueOf(platform_money) -royalty+"";
     	    		    Map<String, Object> map1 = serverDao.selectUserMoney(parent);
   	    	         money1 = map1.get("money")
   	    	                            .toString();
     	    		  serverDao.insertRoyaltyOrder(parent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME,platform_money , null,user_id);
     	    		  //加入服务者余额
     	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
     	    	        hashMap.put("user_id", parent);
     	    	        hashMap.put("money", royalty);
     	    	        serverDao.updateServerUserMoney(hashMap);
     	    	         royaltytotal+=royalty;
     	    	  }else if(!StringTools.isEmpty(selectEntMember22)&&selectEntMember22.equals("1")){
      	    	  	 Double selectRate = Double.parseDouble( selectRate2.get("two_vip_two").toString());
      	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
      	    		 platform_money=  Double.valueOf(platform_money) -royalty+"";
      	    		  Map<String, Object> map1 = serverDao.selectUserMoney(parent);
    	    	         money1 = map1.get("money")
    	    	                            .toString();
      	    		  serverDao.insertRoyaltyOrder(parent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME,platform_money, null,user_id);
      	    		  //加入服务者余额
      	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
      	    	        hashMap.put("user_id", parent);
      	    	        hashMap.put("money", royalty);
      	    	        serverDao.updateServerUserMoney(hashMap);
      	    	      royaltytotal+=royalty;
      	    	  }else{
     	    		 Double selectRate = Double.parseDouble( selectRate2.get("ordinary_two_level").toString());
    	    		  royalty = Double.parseDouble(df.format(money2* (selectRate / 100)));
    	    		  platform_money=  Double.valueOf(platform_money) -royalty+"";
    	    		  Map<String, Object> map1 = serverDao.selectUserMoney(parent);
    	    	         money1 = map1.get("money")
    	    	                            .toString();
    	    		  serverDao.insertRoyaltyOrder(parent, royalty + "", "提成", order.getOrder_id(), Double.valueOf(money1) + royalty + "", Constant.INCOME, platform_money, null,user_id);
    	    		  //加入服务者余额
   	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
   	    	        hashMap.put("user_id", parent);
   	    	        hashMap.put("money", royalty);
   	    	        serverDao.updateServerUserMoney(hashMap);
   	    	       royaltytotal+=royalty;
     	    	  }
     	    	
     	      }
     	      
        }
    	return royaltytotal;
    }
    /**
     * 需求删除
     */
    @Override
    public ReturnData deleteDemand(Integer demandid, Integer orderid, String retractor) {
        if (demandid == null || orderid == null || retractor == null) {
            return new ReturnData(12, "参数有误");
        }
        //查看订单详情
        Order order = serverDao.selectOrderInfo(orderid);
        if (StringTools.isEmpty(order.getRetractor())) {
            order.setRetractor(retractor);
            order.setId(orderid.longValue());
            serverDao.updateOrderRetractor(order);
            int flag = serverDao.deleteDemand(demandid);
        } else {
            order.setRetractor(order.getRetractor() + "," + retractor);
            order.setId(orderid.longValue());
            serverDao.updateOrderRetractor(order);
            int flag = serverDao.deleteDemand(demandid);
            if(flag>0){
                return new ReturnData(200, "成功");
            }else{
                return new ReturnData(200, "失败");
            }
        }
        return new ReturnData(200, "成功");
    }

    /**
     * 需求报名
     */
    @Override
    public ReturnData applyDemand(String demandid, String userid, String longitude, String latitude) {
        if (StringTools.isEmpty(demandid) || StringTools.isEmpty(userid) || StringTools.isEmpty(longitude) || StringTools.isEmpty(latitude)) {
            return new ReturnData(12, "参数有误");
        }
        String selectUsertEnter = userDao.selectUsertEnter(userid);
        if(!StringTools.isEmpty(selectUsertEnter)&& selectUsertEnter.equals("1")){
        		return new ReturnData(20, "您是企业员工，无法进行该操作");
        }
        String selectEnterUser2 = userDao.selectEnterUser(userid);
        Map<String, Object> user = userDao.selectUserIsRegister(userid);
        String age1 = (String) user.get("age");
        if(StringTools.isEmpty(selectEnterUser2)||selectEnterUser2.equals("0")){
            if (StringTools.isEmpty(age1)) {
                return new ReturnData(20, "请先设置年龄");
            }
        }
        //查看需求资料详情
        Map<String, Object> map = serverDao.selectDemandInfo(Integer.parseInt(demandid));
        if(StringTools.isEmpty(selectEnterUser2)||!StringTools.isEmpty(selectEnterUser2)&&!selectEnterUser2.equals("1")){
    		List<Map<String,Object>> selectUserServer = serverDao.selectUserServer(userid);
    		for (Map<String, Object> map2 : selectUserServer) {
    			if(map2.get("server_time")!=null){
    	        	        	try {
    	        					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");

    	        					Date date =  df.parse( map2.get("server_time").toString());
    	        					Date date2 = df.parse( map2.get("end_time").toString());
    	        					Date time =  df.parse(map.get("time").toString());
    	        					if(time.getTime()>=date.getTime()&&time.getTime()<=date2.getTime()){
    	        	 				   return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        					}
    	        					Date time2 =df.parse( map.get("end_time").toString());
    	        					if(time2.getTime()>=date.getTime()&&time2.getTime()<=date2.getTime()){
    	        	 				   return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        					}
    	        					if(time2.getTime()>=date.getTime() &&time.getTime()<=date.getTime()){
    	        						   return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        					}
    	        				} catch (Exception e) {
    	        					// TODO Auto-generated catch block
    	        					  return new ReturnData(12, "当前服务时长以存在待服务订单!");	
    	        				}
    	          }
    		}
    		
    	}
        //查看性别是否符合
        if (map == null) {
            return new ReturnData(19, "此需求已经撤回了");
        }
	    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date	date = df.parse( map.get("time").toString());
			 List<Map<String, Object>> selectUserOrder = serverDao.selectUserOrder(userid);
		        if(selectUserOrder.size()>0){
		        	for (Map<String, Object> map2 : selectUserOrder) {
		        		if(map2.get("audit")==null||map2.get("audit").toString().equals("0")){
		        			Date object = df.parse(map2.get("end_time").toString());
		        			if(date.getTime()<=object.getTime()){
		        				return new ReturnData(20, "您不能预约你服务时间内的需求");
		        			}
		        		}
					}
		        }
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      
        boolean isgender=false;
        String selectEnterUser = userDao.selectEnterUser(userid);
        if(!StringTools.isEmpty(selectEnterUser)&&selectEnterUser.equals("1")){
					isgender=true;
					   if(map.get("gender")!=null&&!StringTools.isEmpty(map.get("gender").toString())){
					ServerOrder	serverOrder = new ServerOrder();
					serverOrder.setUser_id(userid);
					serverOrder.setSex(map.get("gender").toString());
					 List<Map<String,Object>> selectEnterpriseInfoSignUp = enterpriseDao.selectEnterpriseStaffList(serverOrder);
					if(selectEnterpriseInfoSignUp.size()==0){
						return new ReturnData(20, "您没有符合性别要求的员工");
					}
					
					   } 
						ServerOrder	serverOrder = new ServerOrder();
						serverOrder.setUser_id(userid);
					   String age2 = (String) map.get("age");
					   if(!StringTools.isEmpty(age2)){
					         String[] ages = age2.split("-");
								serverOrder.setAge(ages[0]); 
								serverOrder.setAgeend(ages[1]);
								 List<Map<String,Object>> 		selectEnterpriseInfoSignUp = enterpriseDao.selectEnterpriseStaffList(serverOrder);
								if(selectEnterpriseInfoSignUp.size()==0){
									return new ReturnData(20, "您没有符合年龄要求的员工");
								}
					   }
		       
        }
        if(!isgender){
            if(map.get("gender")!=null&&!StringTools.isEmpty(map.get("gender").toString())){
           	 if (!map.get("gender")
                        .equals(user.get("gender"))) {
                    return new ReturnData(19, "您的性别不符合要求");
                }
                }
            //查看年龄是否符合
            String age2 = (String) map.get("age");
            if(!StringTools.isEmpty(age2)){
            String[] ages = age2.split("-");
            if (!(Integer.parseInt(age1) >= Integer.parseInt(ages[0])) || !(Integer.parseInt(age1) <= Integer.parseInt(ages[1]))) {
                return new ReturnData(19, "您的年龄不符合要求");
            }
           }	
        }
        int flag = serverDao.applyDemand(demandid, userid, longitude, latitude);
        //添加自己的消息
        Map<String, Object> hm = new HashMap<>();
        hm.put("title", "报名成功");
        hm.put("type", "1");
        hm.put("recevicer_id", userid);
        hm.put("content", "报名成功");
        messageDao.insertMessage(hm);
        //添加自己的消息
        Map<String, Object> hm2 = new HashMap<>();
        hm2.put("title", "您的需求当前新增1报名人");
        hm2.put("type", "1");
        hm2.put("recevicer_id", map.get("user_id"));
        hm2.put("content", "您的需求当前新增1报名人");
        messageDao.insertMessage(hm2);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 取消需求报名
     */
    @Override
    public ReturnData cancelApplyDemand(String demandid, String userid) {
        if (StringTools.isEmpty(demandid) || StringTools.isEmpty(userid)) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.cancelApplyDemand(demandid, userid);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 我的档期
     */
    @Override
    public ReturnData selectUserAuction(String userid, String type, String byUserid, Integer pageSize, Integer pageNo) {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(type)) {
            return new ReturnData(12, "参数有误");
        }

        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> lists = serverDao.selectUserAuction(userid, type, byUserid);
        if (lists.size() == 0) {
            return new ReturnData(100, "暂无数据");
        }
        for (int i = 0; i < lists.size(); i++) {
            Integer orderid = (Integer) lists.get(i)
                                             .get("id");
            String user_id = (String) lists.get(i)
                                           .get("user_id");
            String server_user_id = (String) lists.get(i)
                                                  .get("server_user_id");
            //查看用户是否评论
            Map<String, Object> map = new HashMap<>();
            map.put("comment_id", userid);
            map.put("service_id", orderid);
            int flag = serverDao.selectIsComment(map);
            if (flag > 0) {
                lists.get(i)
                     .put("isComment", 1);
            } else {
                lists.get(i)
                     .put("isComment", 0);
            }
            
            if(lists.get(i).get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(lists.get(i).get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			lists.get(i).put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
            				lists.get(i).put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			lists.get(i).put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
            				lists.get(i).put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            
        }
		/*if("1".equals(type)){
			//查看我发布的档期
			List<Map<String, Object>> serverList = serverDao.selectMyServer(userid);
			for(int i = 0;i < serverList.size();i++){
				serverList.get(i).put("status", "初始状态");
				if(!StringTools.isEmpty((String)serverList.get(i).get("order_id")) && "1".equals(serverList.get(i).get("order_type"))){
					continue;
				}else{
					lists.add(serverList.get(i));
				}
			}
		}*/
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
        return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
    }

    /**
     * 删除发布服务
     */
    @Override
    public ReturnData deletePublishServer(Integer serverid) {
        if (serverid == null) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.deletePublishServer(serverid);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    /**
     * 档期评价
     */
    @Transactional
    @Override
    public ReturnData auctionAppraise(String star_level, String give_reward, String content, String upload_image,
                                      String user_id, String comment_id, String service_id, String pay_type, String ip, String password) {
        if (StringTools.isEmpty(star_level) || StringTools.isEmpty(user_id) || StringTools.isEmpty(comment_id) || StringTools.isEmpty(service_id)) {
            return new ReturnData(12, "参数有误");
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("star_level", star_level);
        map.put("give_reward", give_reward);
        map.put("content", content);
        map.put("upload_image", upload_image);
        map.put("user_id", user_id);
        map.put("comment_id", comment_id);
        map.put("service_id", service_id);
        Order order = serverDao.selectOrderInfo(Integer.parseInt(service_id));
        map.put("id", order.getOrder_id());
        if (Double.valueOf(give_reward) > 0) {
            // 微信
            if (pay_type.equals("1")) {
                try {
                    serverDao.auctionAppraise_to(map);
                    ReturnData returnData = WxpayDemoUtils5.wxPay("打赏", order.getOrder_id(), give_reward, ip, "");
                    return returnData;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 支付宝
            if (pay_type.equals("2")) {
                try {
                    serverDao.auctionAppraise_to(map);
                    ReturnData returnData = CfbpayDemoUtils5.returnAlipayPayParam("订单打赏", "打赏", order.getOrder_id(), give_reward, "");
                    return returnData;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 钱包
            if (pay_type.equals("3")) {
                Map<String, Object> map1 = serverDao.selectUserMoney(comment_id);
                if (map1 == null) {
                    return new ReturnData(15, "未找到该用户信息");
                }
                String pay_password = (String) map1.get("pay_password");        //用户钱包密码
                if (StringTools.isEmpty(pay_password)) {
                    return new ReturnData(20, "请先设置支付密码");
                }
                Double money = (Double) map1.get("money");        //用户钱包金额
                if (money < Double.valueOf(give_reward)) {
                    return new ReturnData(30, "钱包金额不足，请先充值");
                }
                try {
                    if (!MD5Util.getMD5(password)
                                .equals(pay_password)) {
                        return new ReturnData(40, "密码错误");
                    }
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                //  减去打赏费用
                Double _money = money - Double.valueOf(give_reward);
                serverDao.returnUserMoney(comment_id, _money.toString());


                Map<String, Object> map2 = serverDao.selectUserMoney(user_id);
                if (map2 == null) {
                    return new ReturnData(15, "未找到该用户信息");
                }
                Double money1 = (Double) map2.get("money");
                //  加上打赏费用
                Double _money1 = money1 + Double.valueOf(give_reward);
                serverDao.returnUserMoney(user_id, _money1.toString());
                return getReturnData(star_level, user_id, service_id, map);
            }


        }
        return getReturnData(star_level, user_id, service_id, map);
    }


    public ReturnData getReturnData(String star_level, String user_id, String service_id, Map<String, Object> map) {

        if (map.isEmpty()) {
            return new ReturnData(100, "参数为空");
        } else {
            int auctionAppraise = serverDao.getAuctionAppraise(map);
            if (auctionAppraise == 0) {
                serverDao.auctionAppraise(map);
            }
        }
        String comment_id = map.get("comment_id")
                               .toString();
        String give_reward = map.get("give_reward")
                                .toString();
        Order order = serverDao.selectOrderInfo(Integer.parseInt(service_id));
        serverDao.updateOrderStatus(Integer.parseInt(service_id));
        //查看我的积分
        Map<String, Object> hm = userDao.selectMyIntegral(user_id);
        Integer integral = Integer.parseInt(hm.get("integral")
                                              .toString());    //用户积分
        //查看积分使用方式
        Map<String, Object> hashMap = userDao.selectIntegeralWay();
        Integer five_star = Integer.parseInt(hashMap.get("five_star")
                                                    .toString());    //五星好评获得的积分
        Integer tow_star = Integer.parseInt(hashMap.get("tow_star")
                                                   .toString());    //两星差评扣除的积分
        // 五星差评
        if ("5".equals(star_level)) {
            //添加该用户积分
            integral += five_star;
            //修改用户积分
            int flag2 = payOrderDao.updateUserIntegral(user_id, integral.toString());
            //添加该用户的积分记录
            int f = serverDao.insertIntegralRecord(user_id, five_star + "", "五星好评", null);
        }
        // 二星差评
        if ("2".equals(star_level)) {
            //减少该用户积分
            integral -= tow_star;
            //修改用户积分
            int flag2 = payOrderDao.updateUserIntegral(user_id, integral.toString());
            //添加该用户的积分记录
            int f = serverDao.insertIntegralRecord(user_id, tow_star + "", "两星差评", null);
        }

        //  一星差评
        if ("1".equals(star_level)) {
            //减少该用户积分
            integral -= tow_star;
            //修改用户积分
            int flag2 = payOrderDao.updateUserIntegral(user_id, integral.toString());
            //添加该用户的积分记录
            int f = serverDao.insertIntegralRecord(user_id, tow_star + "", "一星差评", null);
        }
        // 平台余额
        Map<String, Object> map1 = serverDao.selectUserMoney("1");
        Double platform_money = (Double) map1.get("money");

        // 打赏金額未空 就無需記錄了
        if (give_reward != null || give_reward != "" || !give_reward.equals("0")) {
            serverDao.insertCancelOrder(user_id, give_reward, "打赏", order.getOrder_id(), Double.valueOf(serverDao.selectUserMoney(user_id)
                                                                                                                 .get("money")
                                                                                                               .toString()) + "", Constant.EXPEND, platform_money + "", null);
            String selectEntUserId = serverDao.selectEntUserId(comment_id);
            if(!StringTools.isEmpty(selectEntUserId)){
            	comment_id=selectEntUserId;
            }
            serverDao.insertCancelOrder(comment_id, give_reward, "打赏对方", order.getOrder_id(), Double.valueOf(serverDao.selectUserMoney(comment_id)
                                                                                                                      .get("money")
                                                                                                                      .toString()) + "", Constant.INCOME, platform_money + "", null);

        }

        return new ReturnData(200, "成功");

    }

    /**
     * 档期详情
     */
    @Override
    public ReturnData selectAuctionInfo(Integer orderid, String order_type, String userid) {
        if (orderid == null || StringTools.isEmpty(order_type) || StringTools.isEmpty(userid)) {
            return new ReturnData(12, "参数有误");
        }
        //查看用户详情
        Map<String, Object> info = userDao.selectUserIsRegister(userid);
        if ("1".equals(order_type)) {
            Map<String, Object> map = serverDao.selectAuctionInfo(orderid, Integer.parseInt(userid));
            if(map.get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(map.get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			map.put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			map.put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            if (map != null) {
                if (map.get("user_id") != null) {
                    //查看用户详情
                    Map<String, Object> userInfo = userDao.selectUserIsRegister((String) map.get("user_id"));
					/*map.put("longitude", userInfo.get("longitude"));
					map.put("latitude", userInfo.get("latitude"));*/
                    map.put("userPhoto", userInfo.get("photo"));
                    Map<String, Object> userInfo2 = userDao.selectUserIsRegister(userid);
                    map.put("longitude", userInfo2.get("longitude")); 
                    map.put("latitude", userInfo2.get("latitude")); 
                }
                Map<String, Object> selectOrderUsers = serverDao.selectOrderUser( map.get("id").toString());
                if(selectOrderUsers!=null){
                	map.put("staffPhoto", selectOrderUsers.get("photo"));
                	map.put("umobile", selectOrderUsers.get("mobile"));
                	if(!userid.equals(selectOrderUsers.get("id").toString())){
                		map.put("tousuId", selectOrderUsers.get("id"));
                	}else{
                		map.put("tousuId", map.get("user_id"));	
                	}
                    Map<String, Object> userInfo3 = userDao.selectUserIsRegister(selectOrderUsers.get("id").toString());
                    map.put("longitude1", userInfo3.get("longitude")); 
                    map.put("latitude1", userInfo3.get("latitude")); 
                }
                return new ReturnData(map, 200, "成功");
            }
        } else if ("2".equals(order_type)) {
            Map<String, Object> map = serverDao.selectAuctionInfo2(orderid, Integer.parseInt(userid));
            if(map.get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(map.get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			map.put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			map.put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            if (map != null) {
                map.put("longitude", info.get("longitude"));
                map.put("latitude", info.get("latitude"));
                Map<String, Object> selectOrderUsers = serverDao.selectOrderUser( map.get("id").toString());
                if(selectOrderUsers!=null){
                	map.put("staffPhoto", selectOrderUsers.get("photo"));
                	map.put("umobile", selectOrderUsers.get("mobile"));
                	map.put("tousuId", selectOrderUsers.get("id"));
                	   Map<String, Object> userInfo3 = userDao.selectUserIsRegister(selectOrderUsers.get("id").toString());
                       map.put("longitude1", userInfo3.get("longitude")); 
                       map.put("latitude1", userInfo3.get("latitude")); 
                }
                return new ReturnData(map, 200, "成功");
            }
        }
        
        
        return new ReturnData(100, "未找到该信息");
    }

    /**
     * 支付违约金30元
     */
    @Transactional
    @Override
    public ReturnData payDamages(String userid, String gainUserid, String payMethod, String body, String subject, String payMoney,
                                 String ip, String password, String oid, String type) throws Exception {
        if (StringTools.isEmpty(userid) || StringTools.isEmpty(payMethod) || StringTools.isEmpty(body) || StringTools.isEmpty(subject) ||
                StringTools.isEmpty(payMoney) || StringTools.isEmpty(gainUserid) || StringTools.isEmpty(oid)) {
            return new ReturnData(12, "参数有误");
        }

        ReturnData ReturnData = new ReturnData();
        String orderid = WxpayDemoUtils.getRandomString(16);
        if ("1".equals(payMethod)) {
            ReturnData = WxpayDemoUtils3.wxPay(body, orderid, payMoney, ip, userid + "," + gainUserid + "," + oid + "," + type + "," + payMoney);
        } else if ("2".equals(payMethod)) {
            ReturnData = CfbpayDemoUtils3.returnAlipayPayParam(body, subject, oid, payMoney, userid + "," + gainUserid + "," + oid + "," + type + "," + payMoney);
        } else if ("3".equals(payMethod)) {
            Map<String, Object> map = serverDao.selectUserMoney(userid);
            if (map == null) {
                return new ReturnData(15, "未找到该用户信息");
            }
            String pay_password = (String) map.get("pay_password");        //用户钱包密码
            if (StringTools.isEmpty(pay_password)) {
                return new ReturnData(20, "请先设置支付密码");
            }
            Double money = (Double) map.get("money");        //用户钱包金额
            if (money < 29D) {
                return new ReturnData(30, "钱包金额不足，请先充值");
            }
            if (!MD5Util.getMD5(password)
                        .equals(pay_password)) {
                return new ReturnData(40, "密码错误");
            }
            if ("1".equals(type)) {
                //修改订单状态为服务中
                serverDao.updateOrderStatuIsServer(Integer.parseInt(oid));
            } else {
                //修改订单状态为已取消
                serverDao.updateOrderStatu(Integer.parseInt(oid));

				/*if("1".equals(order.getOrder_type())){
					//删除服务
					serverDao.deleteServer(Integer.parseInt(order.getServer_id()));
				}else{
					//删除需求
					serverDao.deleteDemand(Integer.parseInt(order.getServer_id()));
				}*/
            }
            // 获取平台余额
            Map<String, Object> map1 = serverDao.selectUserMoney("1");
            String platform_money = map1.get("money")
                                        .toString();
            //查看订单详情
            Order order = serverDao.selectOrderInfo(Integer.valueOf(oid));
            if (order != null) {
             	Long time = System.currentTimeMillis();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    				Date dt1 = df.parse(order.getServer_time());
    				long time2 = dt1.getTime()+30*1000*60;//在当前开始时间的基础上往后加30分钟
    				if(time2<=time){ 
    					if(time2<=time){
    				            Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getServer_user_id());
    				            Double money1 = (Double) selectUserMoney.get("money");
    				            if (money1 >= 30) {
    				            Map<String, Object> selectUserMoney2 = serverDao.selectUserMoney(order.getUser_id());
    				            Double money2 = (Double) selectUserMoney2.get("money");
    						 serverDao.insertCancelOrder(order.getServer_user_id(), "30", "服务违约支出", order.getOrder_id(), Double.valueOf(money1) - Double.valueOf(30) + "", Constant.EXPEND, platform_money, null);
    				            serverDao.returnUserMoney(order.getServer_user_id(), money1 - Double.valueOf(30) + ""); 
    						 serverDao.insertCancelOrder(order.getUser_id(), "30", "服务方违约金收入", order.getOrder_id(), money2 +Double.valueOf(30)+ "", Constant.INCOME, platform_money, null);
    						 serverDao.returnUserMoney(order.getUser_id(), money2 + Double.valueOf(30) + ""); } else {
    				                // 或者新增违约金记录 （用于充值的时候进行扣除）
    				                serverDao.insertViolate(30.00,  order.getServer_user_id(), order.getOrder_id(), order.getUser_id());
    				            }
    					}
    				}else{
                if (order.getOrder_type()
                         .equals("2")) {
                    quxiaoOrder(userid, payMoney, platform_money, order);
                } else if (order.getOrder_type()
                                .equals("1")) {
                    quxiaoOrder(userid, payMoney, platform_money, order);
                }
                if (!StringTools.isEmpty(order.getDiscountid())) {
                    //修改优惠券状态
                    serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
                }
                String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
        		if(!order.getReality_price().equals("0.00")){
        		selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price().substring(0,order.getReality_price().indexOf("."))));
        		serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
                serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
                }
                if (!StringTools.isEmpty(order.getIntegral())) {
                    //退还用户积分
                    serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
                    //最后添加该用户的积分记录
                    serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);
                }
               /* if (!StringTools.isEmpty(order.getIntegral())) {
                    //退还用户积分
                    serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Double.valueOf(serverDao.selectUserIntegral(order.getUser_id())) +Double.valueOf(order.getIntegral())));
                }*/
                //添加自己的消息
                insertMsg(userid, order);}
            } else {
                return new ReturnData(100, "订单不存在");
            }
            return new ReturnData(200, "支付成功");
        } else {
            return new ReturnData(10, "支付方式有误");
        }
        return ReturnData;
    }

    private void quxiaoOrder(String userid, String payMoney, String platform_money, Order order) {
        if (order.getUser_id()
                 .equals(userid)) {
				 // 1  先进行扣除违约金
	            Map<String, Object> map5 = serverDao.selectUserMoney(order.getUser_id());
	            String user_money1 = map5.get("money")
	                                     .toString();
	            // 2   返回订单金额
	            Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
	            if(selectCancelOrder==null){
	            	serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "", Constant.INCOME, Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", null);
	            	serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "");
	            	serverDao.returnUserMoney("1", Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "");
	            }
	            if(Double.valueOf(user_money1)>=30){
	            	  map5 = serverDao.selectUserMoney(order.getUser_id());
	  	             user_money1 = map5.get("money")
	  	                                     .toString();
	            	serverDao.insertCancelOrder(order.getUser_id(), payMoney, "需方违约支出", order.getOrder_id(), Double.valueOf(user_money1) - Double.valueOf(payMoney) + "", Constant.EXPEND,  Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", null);
	            	serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money1) - Double.valueOf(payMoney) + "");
	            	//  3  服务方获取违约金
	            	Map<String, Object> map3 = serverDao.selectUserMoney(order.getServer_user_id());
	            	String server_money = map3.get("money")
	            			.toString();
	            	serverDao.insertCancelOrder(order.getServer_user_id(), payMoney, "需方违约收入", order.getOrder_id(), Double.valueOf(server_money) + Double.valueOf(payMoney) + "", Constant.INCOME,  Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", null);
	            	serverDao.returnUserMoney(order.getServer_user_id(), Double.valueOf(server_money) + Double.valueOf(payMoney) + "");
	            }else{
	                serverDao.insertViolate(30.00,   order.getUser_id(), order.getOrder_id(),order.getServer_user_id());

	            }
	            //  4 平台返回订单金额
	            //serverDao.insertCancelOrder("1", order.getReality_price(), "平台预付返还", order.getOrder_id(), Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", Constant.EXPEND);
	      
             }
        if (order.getServer_user_id()
                 .equals(userid)) {
            //  1 先获取服务方的钱包
            Map<String, Object> map3 = serverDao.selectUserMoney(userid);
            String server_money = map3.get("money")
                                      .toString();
            if(Double.valueOf(server_money)>=30){
            	serverDao.insertCancelOrder(userid, payMoney, "服务违约支出", order.getOrder_id(), Double.valueOf(server_money) - Double.valueOf(payMoney) + "", Constant.EXPEND, platform_money, null);
            	serverDao.returnUserMoney(userid, Double.valueOf(server_money) - Double.valueOf(payMoney) + "");
            	// 3 需求方获取违约金
            	Map<String, Object> map4 = serverDao.selectUserMoney(order.getUser_id());
            	String user_money = map4.get("money")
            			.toString();
            	serverDao.insertCancelOrder(order.getUser_id(), payMoney, "服务方违约金收入", order.getOrder_id(), Double.valueOf(user_money) + Double.valueOf(payMoney) + "", Constant.INCOME, platform_money, null);
            	serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money) + Double.valueOf(payMoney) + "");
            }
         	// 4 需求方获取订单返回金额
        	Map<String, Object> map5 = serverDao.selectUserMoney(order.getUser_id());
        	String user_money1 = map5.get("money")
        			.toString();
            // 2 扣除服务方违约金
        	   Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
	            if(selectCancelOrder==null){
	            	   serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "", Constant.INCOME, Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", null);
	                   serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "");
	                   // 5 平台返回订单金额
	                   //  serverDao.insertCancelOrder("1", order.getReality_price(), "平台预付返还", order.getOrder_id(), Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", Constant.EXPEND);
	                   serverDao.returnUserMoney("1", Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "");
	            }
                 }
    }

    /**
     * 我发布的需求
     */
    @Override
    public ReturnData selectUserIssueDemand(String userid, Integer pageSize, Integer pageNo) {
        if (StringTools.isEmpty(userid)) {
            return new ReturnData(12, "参数有误");
        }
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> lists = serverDao.selectUserIssueDemand(userid);
        if (lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                String orderid = lists.get(i)
                                      .get("orderid")
                                      .toString();
                String server_user_id = (String) lists.get(i)
                                                      .get("server_user_id");
                String user_id = (String) lists.get(i)
                                               .get("user_id");
                //查看用户是否评论
                Map<String, Object> map = new HashMap<>();
                map.put("comment_id", userid);
                map.put("service_id", orderid);
                int flag = serverDao.selectIsComment(map);
                if (flag > 0) {
                    lists.get(i)
                         .put("isComment", 1);
                } else {
                    lists.get(i)
                         .put("isComment", 0);
                }
                
                if(lists.get(i).get("order_id")!=null){
                	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(lists.get(i).get("order_id").toString());
                	for (Map<String, Object> map2 : selectAppeal) {
                		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
                			 lists.get(i).put("is_status", 0);
                			if(map2.get("is_acceptance").toString().equals("1")){
                				lists.get(i).put("is_status", 3);
                    			break;
                    		}
                		}
                		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
                			lists.get(i).put("is_status", 1);
                			if(map2.get("is_acceptance").toString().equals("1")){
                				lists.get(i).put("is_status", 3);
                    			break;
                    		}
                		}
                	}
                }else{
                	lists.get(i).put("is_status", null);
                }
                
                
            }
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
            return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
        }
        return new ReturnData(100, "暂无数据");
    }

    /**
     * 我报名的需求
     */
    @Override
    public ReturnData selectUserApplyDemand(String userid, Integer pageSize, Integer pageNo) {
        if (StringTools.isEmpty(userid)) {
            return new ReturnData(12, "参数有误");
        }
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> lists = serverDao.selectUserApplyDemand(userid);
        if (lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                String orderid = lists.get(i)
                                      .get("orderid")
                                      .toString();
                String server_user_id = (String) lists.get(i)
                                                      .get("server_user_id");
                String user_id = (String) lists.get(i)
                                               .get("userid");
                //查看用户是否评论
                Map<String, Object> map = new HashMap<>();
                map.put("comment_id", userid);
                map.put("service_id", orderid);
                int flag = serverDao.selectIsComment(map);
                if (flag > 0) {
                    lists.get(i)
                         .put("isComment", 1);
                } else {
                    lists.get(i)
                         .put("isComment", 0);
                }
                if(lists.get(i).get("order_id")!=null){
                	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(lists.get(i).get("order_id").toString());
                	for (Map<String, Object> map2 : selectAppeal) {
                		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
                			lists.get(i).put("is_status", 0);
                			if(map2.get("is_acceptance").toString().equals("1")){
                				lists.get(i).put("is_status", 3);
                    			break;
                    		}
                		}
                		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
                			lists.get(i).put("is_status", 1);
                			if(map2.get("is_acceptance").toString().equals("1")){
                				lists.get(i).put("is_status", 3);
                    			break;
                    		}
                		}
                	}
                }else{
                	lists.get(i).put("is_status", null);
                }
                
                
            }
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
            return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
        }
        return new ReturnData(100, "暂无数据");
    }

    /**
     * 我的需求详情
     */
    @Override
    public ReturnData selectUserDemandInfo(Integer demandid, Integer type, String longitude, String latitude, String userid) {
        if (demandid == null || type == null || StringTools.isEmpty(longitude) || StringTools.isEmpty(latitude)) {
            return new ReturnData(12, "参数有误");
        }
        Integer uid = null;
        if (!StringTools.isEmpty(userid)) {
            uid = Integer.parseInt(userid);
        }
        //查看用户详情
        Map<String, Object> userInfo = userDao.selectUserIsRegister(userid);
        if (type == 1) {
            Map<String, Object> map = serverDao.selectUserDemandInfo(demandid, uid);
            if (map == null) {
                return new ReturnData(100, "未找到相关信息");
            }
            if(map.get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(map.get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			map.put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			map.put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            List<Map<String, Object>> lists = serverDao.selectApplyUserInfo(demandid);
            for (int i = 0; i < lists.size(); i++) {
                //计算距离
                Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                        .parseDouble(lists.get(i)
                                          .get("latitude")
                                          .toString()), Double.parseDouble(lists.get(i)
                                                                                .get("longitude")
                                                                                .toString()));
                lists.get(i)
                     .put("distance", distance);
                if (lists.get(i)
                         .get("avg") == null) {
                    lists.get(i)
                         .put("avg", 4);
                }
            }
            map.put("lists", lists);
            if (userInfo != null) {
                map.put("longitude", userInfo.get("longitude"));
                map.put("latitude", userInfo.get("latitude"));
                map.put("umobile", userInfo.get("mobile"));
                map.put("server_user_id", userInfo.get("id"));
            }
            if(map.get("orderid")!=null){
                Map<String, Object> selectOrderUser = serverDao.selectOrderUser( map.get("orderid").toString());
                if(selectOrderUser!=null){
                	map.put("umobile", selectOrderUser.get("mobile"));
                	map.put("tousuId", selectOrderUser.get("id"));
                	map.put("staffPhoto", selectOrderUser.get("photo"));
                    Map<String, Object> userInfo3 = userDao.selectUserIsRegister(selectOrderUser.get("id").toString());
                    map.put("longitude1", userInfo3.get("longitude")); 
                    map.put("latitude1", userInfo3.get("latitude")); 
                }else{
                     Order selectOrderInfo = serverDao.selectOrderInfo(Integer.parseInt(map.get("oid").toString()));
                     if(!StringTools.isEmpty(selectOrderInfo.getServer_user_id())){
                    	 Map<String, Object> userInfo3 = userDao.selectUserIsRegister(selectOrderInfo.getServer_user_id());
                    	 map.put("longitude1", userInfo3.get("longitude")); 
                    	 map.put("latitude1", userInfo3.get("latitude")); 
                     }
                }
            }
       
            
            return new ReturnData(map, 200, "成功");
        } else if (type == 2) {
            Map<String, Object> map = serverDao.selectUserDemandInfo(demandid, uid);
            if (map == null) {
                return new ReturnData(100, "未找到相关信息");
            }
            if(map.get("order_id")!=null){
            	List<Map<String,Object>> selectAppeal = serverDao.selectAppeal(map.get("order_id").toString());
            	for (Map<String, Object> map2 : selectAppeal) {
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("0")){
            			map.put("is_status", 0);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            		if(map2.get("is_status")!=null&&map2.get("is_status").toString().equals("1")){
            			map.put("is_status", 1);
            			if(map2.get("is_acceptance").toString().equals("1")){
                			map.put("is_status", 3);
                			break;
                		}
            		}
            	}
            }else{
            	map.put("is_status", null);
            }
            if (userInfo != null) {
                map.put("longitude", userInfo.get("longitude"));
                map.put("latitude", userInfo.get("latitude"));
                map.put("umobile", userInfo.get("mobile"));
                map.put("server_user_id", userInfo.get("id"));
            }
            if(map.get("orderid")!=null){
                Map<String, Object> selectOrderUser = serverDao.selectOrderUser( map.get("orderid").toString());
                if(selectOrderUser!=null){
                	map.put("umobile", selectOrderUser.get("mobile"));
                	map.put("tousuId", selectOrderUser.get("id"));
                	map.put("staffPhoto", selectOrderUser.get("photo"));
                    Map<String, Object> userInfo3 = userDao.selectUserIsRegister(selectOrderUser.get("id").toString());
                    map.put("longitude1", userInfo3.get("longitude")); 
                    map.put("latitude1", userInfo3.get("latitude")); 
                }else{
                    Order selectOrderInfo = serverDao.selectOrderInfo(Integer.parseInt(map.get("oid").toString()));
                    if(!StringTools.isEmpty(selectOrderInfo.getServer_user_id())){
                    Map<String, Object> userInfo3 = userDao.selectUserIsRegister(selectOrderInfo.getServer_user_id());
                   map.put("longitude1", userInfo3.get("longitude")); 
                   map.put("latitude1", userInfo3.get("latitude")); 
                   }
               }
            }
            return new ReturnData(map, 200, "成功");
        }
        return new ReturnData(22, "类型有误");
    }

    /**
     * 首页
     */
    @Override
    public ReturnData selectIndexList(String address, String longitude, String latitude, Integer pageSize, Integer pageNo) {
        if (StringTools.isEmpty(address) || StringTools.isEmpty(longitude) || StringTools.isEmpty(latitude)) {
            return new ReturnData(12, "参数有误");
        }
        address += "%";
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> lists = serverDao.selectIndexList(address);
        if (lists.size() == 0) {
            return new ReturnData(100, "暂无数据");
        }
        for (int i = 0; i < lists.size(); i++) {
            //计算距离
            Integer distance = (int) LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double
                    .parseDouble(lists.get(i)
                                      .get("latitude")
                                      .toString()), Double.parseDouble(lists.get(i)
                                                                            .get("longitude")
                                                                            .toString()));
            lists.get(i)
                 .put("distance", distance);
            if (lists.get(i)
                     .get("star_level") == null) {
                lists.get(i)
                     .put("star_level", 4);
            }
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
        return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
    }

    /**
     * 开始服务
     */
    @Override
    public ReturnData updateOrderStatuIsServer(Integer id) {
        if (id == null) {
            return new ReturnData(12, "参数有误");
        }
        Order order = serverDao.selectOrderInfo(id);
        if (order != null) {
        	Long time = System.currentTimeMillis();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            try {
				Date dt1 = df.parse(order.getServer_time());
				long time2 = dt1.getTime()+30*1000*60;//在当前开始时间的基础上往后加30分钟
				if(time>=time2){
					  Map<String, Object> map1 = serverDao.selectUserMoney("1");
			            String platform_money = map1.get("money")
			                                        .toString();
			            Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getServer_user_id());
			            Double money = (Double) selectUserMoney.get("money");
			            if (money >= 30) {
			            Map<String, Object> selectUserMoney2 = serverDao.selectUserMoney(order.getUser_id());
			            Double money2 = (Double) selectUserMoney2.get("money");
					 serverDao.insertCancelOrder(order.getServer_user_id(), "30", "服务违约支出", order.getOrder_id(), Double.valueOf(money) - Double.valueOf(30) + "", Constant.EXPEND, platform_money, null);
			            serverDao.returnUserMoney(order.getServer_user_id(), money - Double.valueOf(30) + ""); 
					 serverDao.insertCancelOrder(order.getUser_id(), "30", "服务方违约金收入", order.getOrder_id(), money2+ Double.valueOf(30)  + "", Constant.INCOME, platform_money, null);
					 serverDao.returnUserMoney(order.getUser_id(), money2 + Double.valueOf(30) + ""); 
			            } else {
			                // 或者新增违约金记录 （用于充值的时候进行扣除）
			                serverDao.insertViolate(30.00,  order.getServer_user_id(), order.getOrder_id(), order.getUser_id());
			            }
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        int flag = serverDao.updateOrderStatuIsServer(id);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }
	

    /**
     * 订单提交完成
     */
    @Override
    public ReturnData orderSubmitFinish(Integer orderid) {
        if (orderid == null) {
            return new ReturnData(12, "参数有误");
        }
        int flag = serverDao.orderSubmitFinish(orderid);
        if (flag > 0) {
            return new ReturnData(200, "成功");
        }
        return new ReturnData(100, "失败");
    }

    public ReturnData vipList(String userId) {
        if (userId != null) {
            int selectUserAuthentication2 = userDao.selectUserAuthentication(userId);
        	if(selectUserAuthentication2==1){
        		   Map<String, Object> stringObjectMap = vipSettingDao.byUserVipList(2);
        		   List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
        		   list.add(stringObjectMap);
        		   return new ReturnData(list, 200, "成功");
        	}else{
        		List<Map<String, Object>> stringObjectMap = vipSettingDao.userVipList();
                   return new ReturnData(stringObjectMap, 200, "成功");
        	}
          /*  int num = identityAuthenticationDao.selectByUserId(userId);
            if (num > 0) {
                Map<String, Object> stringObjectMap = vipSettingDao.byUserVipList(2);
                return new ReturnData(stringObjectMap, 200, "成功");
            } else {
                Map<String, Object> stringObjectMap = vipSettingDao.byUserVipList(1);
                return new ReturnData(stringObjectMap, 200, "成功");
            }*/
        } else {
            return new ReturnData(100, "用户不存在");
        }

    }

    public ReturnData cancelOrder(String userid, Integer orderid) {

        if (orderid == null || userid == null) {
            return new ReturnData(12, "参数有误");
        }
        //查看订单详情
        Order order = serverDao.selectOrderInfo(orderid);
        if (order == null) {
            return new ReturnData(100, "未找到相关信息");
        }
        //两小时没有服务后取消订单自动扣除服务方30元违金给需方
        if (order != null) {
        	Long time = System.currentTimeMillis();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            try {
				Date dt1 = df.parse(order.getServer_time());
				if(new Date().getTime()>=dt1.getTime()){
					  if (!StringTools.isEmpty(order.getDiscountid())) {
				            //修改优惠券状态
				            serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
				        }
						String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
						if(!order.getReality_price().equals("0.00")){
						selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price().substring(0,order.getReality_price().indexOf("."))));
						serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
			            serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
			            }
			            if (!StringTools.isEmpty(order.getIntegral())) {
				            //退还用户积分
				            serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
				            //最后添加该用户的积分记录
				            serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);
				        }
			       String str="服务违约支出";
			            String str1="服务方违约金收入";
			            /* 	if(order.getUser_id().equals(userid)){
			        		if(!order.getStatus().equals("服务中")){
			        			order.setUser_id(order.getServer_user_id());
				        		order.setServer_user_id(userid);
				        		   str="需方违约支出";
						             str1="需方违约金收入";
			        		}
			        	
			        	}*/
					   Map<String, Object> map1 = serverDao.selectUserMoney("1");
			            String platform_money = map1.get("money")
			                                        .toString();
					 //  1 先获取服务方的钱包
		            Map<String, Object> map3 = serverDao.selectUserMoney(order.getServer_user_id());
		            String server_money = map3.get("money")
		                                      .toString();
		        if (Double.valueOf(server_money) >= 30) {
		        	  // 2 扣除服务方违约金
		            serverDao.insertCancelOrder(order.getServer_user_id(), "30", str, order.getOrder_id(), Double.valueOf(server_money) - Double.valueOf("30") + "", Constant.EXPEND, platform_money, null);
		            serverDao.returnUserMoney(order.getServer_user_id(), Double.valueOf(server_money) - Double.valueOf("30") + "");
		            // 3 需求方获取违约金
		            Map<String, Object> map4 = serverDao.selectUserMoney(order.getUser_id());
		            String user_money = map4.get("money")
		                                    .toString();
		            serverDao.insertCancelOrder(order.getUser_id(), "30", str1, order.getOrder_id(), Double.valueOf(user_money) + Double.valueOf("30") + "", Constant.INCOME, platform_money, null);
		            serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money) + Double.valueOf("30") + "");
		            // 4 需求方获取订单返回金额
		            Map<String, Object> map5 = serverDao.selectUserMoney(order.getUser_id());
		            String user_money1 = map5.get("money")
		                                     .toString();
		            Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
		            if(selectCancelOrder==null){
		                serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "", Constant.INCOME, Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", null);
			            serverDao.returnUserMoney(order.getUser_id(), Double.valueOf(user_money1) + Double.valueOf(order.getReality_price()) + "");
			            // 5 平台返回订单金额
			            //  serverDao.insertCancelOrder("1", order.getReality_price(), "平台预付返还", order.getOrder_id(), Double.valueOf(platform_money) - Double.valueOf(order.getReality_price()) + "", Constant.EXPEND);
			            serverDao.returnUserMoney("1",Double.valueOf(platform_money)- Double.valueOf(order.getReality_price()) +"");
			    		            }
		                } else {
		                // 或者新增违约金记录 （用于充值的时候进行扣除）
		            	serverDao.insertViolate(30.00, userid, order.getOrder_id(), order.getServer_user_id());
		                Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getUser_id());
		                Double money = (Double) selectUserMoney.get("money");
		                Double realityMoney = Double.parseDouble(order.getReality_price()) + money;
		                // 先把订单的钱退回
		                String s = userDao.selectUserMoney("1");
		                Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
			            if(selectCancelOrder==null){
			            	serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), realityMoney + "", Constant.INCOME, Double.valueOf(s) - Double.valueOf(order.getReality_price()) + "", null);
			            	serverDao.returnUserMoney("1", Double.valueOf(platform_money) - Double.valueOf(order.getReality_price())+"");
			                serverDao.returnUserMoney(order.getUser_id(), realityMoney.toString());
	
			            }
		            }
		            int flag4 = serverDao.cancelOrder(orderid);
		            if (flag4 > 0) {
		                return new ReturnData(200, "取消订单成功!");
		            }
				}
				
				/*long time2 = dt1.getTime()+120*1000*60;//在当前开始时间的基础上往后加30分钟
				if(time2<=time){
				     Map<String, Object> map1 = serverDao.selectUserMoney("1");
			            String platform_money = map1.get("money")
			                                        .toString();
			            Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getServer_user_id());
			            Double money = (Double) selectUserMoney.get("money");
			            if (money >= 30) {
			            Map<String, Object> selectUserMoney2 = serverDao.selectUserMoney(order.getUser_id());
			            Double money2 = (Double) selectUserMoney2.get("money");
					 serverDao.insertCancelOrder(order.getServer_user_id(), "30", "服务违约支出", order.getOrder_id(), Double.valueOf(money) - Double.valueOf(30) + "", Constant.EXPEND, platform_money, null);
		                serverDao.insertCancelOrder(order.getUser_id(), "30", "服务方违约金收入", order.getOrder_id(), money2 +30+ "", Constant.INCOME, platform_money, null);
			            } else {
			                // 或者新增违约金记录 （用于充值的时候进行扣除）
			                serverDao.insertViolate(30.00,  order.getServer_user_id(), order.getOrder_id(), userid);
			            }
			            }*/
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        Date end = null;
        Date start = null;
        try {
            end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(order.getEnd_time());
            start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(order.getServer_time());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date dated = new Date();
        Long nowTime = dated.getTime()+120*1000*60;
        if (new Date().getTime() > start.getTime()) {
            if (userid.equals(order.getUser_id())) {
                //添加自己的消息
                insertMsg(userid, order);
            }
            if (!StringTools.isEmpty(order.getDiscountid())) {
                //修改优惠券状态
                serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
            }
        	String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
        	if(Double.valueOf(order.getReality_price())>0){

        	selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price()));
            serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
            serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
         	}
            if (!StringTools.isEmpty(order.getIntegral())) {
                //退还用户积分
                serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
                serverDao.insertIntegralRecord(order.getUser_id(), String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())), "积分返还", null);
            }
            //查看用户余额
            Map<String, Object> selectUserMoney = serverDao.selectUserMoney(order.getUser_id());
            Double money = (Double) selectUserMoney.get("money");
            Double realityMoney = Double.parseDouble(order.getReality_price()) + money;
            // 先把订单的钱退回
            String s = userDao.selectUserMoney("1");

            Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
            if(selectCancelOrder==null){
            	serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(), realityMoney + "", Constant.INCOME, Double.valueOf(s) - Double.valueOf(order.getReality_price()) + "", null);
            	serverDao.returnUserMoney("1",  Double.valueOf(s) - Double.valueOf(order.getReality_price())+"");
                serverDao.returnUserMoney(order.getUser_id(), realityMoney.toString());
	       
            }
            // 在查询对方是否余额是否够30元
            Map<String, Object> stringObjectMap = serverDao.selectUserMoney(order.getServer_user_id());
            Double money1 = (Double) stringObjectMap.get("money");
            Double money2 = realityMoney + 30;
            if (money1 >= 30) {
                String s1 = userDao.selectUserMoney("1");
                serverDao.returnUserMoney(order.getUser_id(), money2.toString());
                serverDao.insertCancelOrder(order.getUser_id(), "30", "服务方违约金收入", order.getOrder_id(), money2 + "", Constant.INCOME, s1, null);
                Double money3 = money1 - 30;
                serverDao.returnUserMoney(order.getServer_user_id(), money3.toString());
                serverDao.insertCancelOrder(order.getServer_user_id(), "30", "服务违约支出", order.getOrder_id(), money3 + "", Constant.INCOME, s1, null);
            } else {
                // 或者新增违约金记录 （用于充值的时候进行扣除）
                serverDao.insertViolate(30.00, userid, order.getOrder_id(), order.getServer_user_id());
                
            }
            int flag4 = serverDao.cancelOrder(orderid);
            if (flag4 > 0) {
                return new ReturnData(200, "取消订单成功!");
            }
        }
        return null;
    }
    /**
     * 修改服务
     */
	@Override
	public ReturnData updatePublishServer(ServerOrder server) {
		  if (StringTools.isEmpty(server.getId().toString()) ) {
	            return new ReturnData(12, "参数有误");
	        }
	        //查看用户身份证是否已经认证
/*	        int counts = userDao.selectUserIdentity(server.getUser_id());
	        if (counts == 0) {
	            return new ReturnData(24, "请先进行身份认证");
	        }*/
			/*//查看用户是否是vip
			Map<String, Object> map = vipDao.selectVipPage(server.getUser_id());
			if(map == null){
				return new ReturnData(24,"您还不是vip用户，请先成为vip");
			}*/
	        int flag = serverDao.updatePublishServer(server);
	        if (flag == 1) {
	            //修改订单
	            Order order = new Order();
	            order.setServer_id(server.getId()
	                                     .toString());
	            order.setServer_user_id(server.getUser_id());
	            order.setPrice(server.getPrice());
	            order.setOrder_type("1");
	            order.setStatus("初始状态");
	            int flag1 = serverDao.updateNowMake(order);
	            //添加自己的消息
	            Map<String, Object> hm = new HashMap<>();
	            hm.put("title", "修改服务成功");
	            hm.put("type", "1");
	            hm.put("recevicer_id", server.getUser_id());
	            hm.put("content", "修改服务成功");
	            hm.put("record_id", server.getId()
	                                      .toString());
	            messageDao.insertMessage(hm);
	            //添加推荐人消息
	            List<Map<String, Object>> lists = serverDao.selectRecommendDemand();
	            List<Map<String, Object>> arrayList = new ArrayList<>();
	            for (int k = 0; k < lists.size(); k++) {
	                O:
	                for (int i = 0; i < server.getDetails()
	                                          .length(); i++) {
	                    for (int j = 0; j < ((String) lists.get(k)
	                                                       .get("details")).length(); j++) {
	                        Character charAt = server.getDetails()
	                                                 .charAt(i);
	                        Character charAt2 = ((String) lists.get(k)
	                                                           .get("details")).charAt(j);
	                        System.out.println(charAt.equals(charAt2));
	                        if (server.getDetails()
	                                  .charAt(i) == ((String) lists.get(k)
	                                                               .get("details")).charAt(j)) {
	                            arrayList.add(lists.get(k));
	                            break O;
	                        }
	                    }
	                }
	            }
	            for (int i = 0; i < arrayList.size(); i++) {
	                Map<String, Object> map = new HashMap<>();
	                map.put("title", "您有一条新的服务信息");
	                map.put("type", "1");
	                map.put("recevicer_id", arrayList.get(i)
	                                                 .get("user_id"));
	                map.put("content", "您有一条新的服务信息");
	                map.put("record_id", server.getId()
	                                           .toString());
	                messageDao.insertMessage(map);
	                AuroraPush.pushTargetForDriver(arrayList.get(i)
	                                                        .get("user_id")
	                                                        .toString(), "您有一条新的服务信息!");
	            }
	            return new ReturnData(server.getDetails(), 200, "成功");
	        }
	        return new ReturnData(100, "失败");
	}
	/**
	 * 修改需求
	 */
	@Override
	public ReturnData updatePublishDemand(DemandOrder server) {
		if (StringTools.isEmpty(server.getId().toString()) ) {
            return new ReturnData(12, "参数有误");
        }
	        //查看用户身份证是否已经认证
	        int count = userDao.selectUserIdentity(server.getUser_id());
	        String selectEnterUser = userDao.selectEnterUser(server.getUser_id());
	        if(!StringTools.isEmpty(selectEnterUser)&&selectEnterUser.equals("1")){
	        	count=1;
	        }
	        if (count == 0) {
	            return new ReturnData(24, "请先进行身份认证");
	        }
			/*//查看用户是否是vip
			Map<String, Object> map = vipDao.selectVipPage(server.getUser_id());
			if(map == null){
				return new ReturnData(24,"您还不是vip用户，请先成为vip");
			}*/
	        server.setNumber(WxpayDemoUtils.getRandomString(16));
	        int flag = serverDao.updatePublishDemand(server);
	        if (flag == 1) {
	            //添加订单
	            Order order = new Order();
	            order.setServer_id(server.getId()
	                                     .toString());
	            order.setUser_id(server.getUser_id());
	            order.setPrice(server.getPrice());
	            order.setOrder_type("2");
	            order.setStatus("初始状态");
	            int flag1 = serverDao.updateNowMake(order);
	            //添加自己的消息
	            Map<String, Object> hm = new HashMap<>();
	            hm.put("title", "修改需求成功");
	            hm.put("type", "1");
	            hm.put("recevicer_id", server.getUser_id());
	            hm.put("content", "修改需求成功");
	            hm.put("record_id", server.getId()
	                                      .toString());
	            messageDao.insertMessage(hm);
	            List<Map<String, Object>> lists = serverDao.selectRecommendServer();
	            List<Map<String, Object>> arrayList = new ArrayList<>();
	            for (int k = 0; k < lists.size(); k++) {
	                O:
	                for (int i = 0; i < server.getDetails()
	                                          .length(); i++) {
	                    for (int j = 0; j < ((String) lists.get(k)
	                                                       .get("details")).length(); j++) {
	                        if (server.getDetails()
	                                  .charAt(i) == ((String) lists.get(k)
	                                                               .get("details")).charAt(j)) {
	                            arrayList.add(lists.get(k));
	                            break O;
	                        }
	                    }
	                }
	            }
	            for (int i = 0; i < arrayList.size(); i++) {
	                Map<String, Object> map = new HashMap<>();
	                map.put("title", "您有一条新的需求信息");
	                map.put("type", "1");
	                map.put("recevicer_id", arrayList.get(i)
	                                                 .get("user_id"));
	                map.put("content", "您有一条新的需求信息");
	                map.put("record_id", server.getId()
	                                           .toString());
	                messageDao.insertMessage(map);
	                AuroraPush.pushTargetForDriver(arrayList.get(i)
	                                                        .get("user_id")
	                                                        .toString(), "您有一条新的需求信息!");
	            }
	            return new ReturnData(server.getDetails(), 200, "成功");
	        }
	        return new ReturnData(100, "失败");
	}


}
